win-variant 0.3.0

This is a rust crate that aims to provide a more ergonomic way of working with variants in winapi based projects.
Documentation
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use std::{
    convert::{TryFrom, TryInto},
    ptr,
};

use log::trace;
use widestring::U16CString;
use winapi::{
    shared::{
        minwindef::{UINT, ULONG},
        winerror::NOERROR,
        wtypes::{
            VARTYPE, VT_BOOL, VT_BSTR, VT_EMPTY, VT_I2, VT_I4, VT_I8, VT_INT, VT_R4, VT_R8,
            VT_SAFEARRAY, VT_UI2, VT_UI4, VT_UI8, VT_UINT,
        },
    },
    um::{
        oaidl::{SAFEARRAY, SAFEARRAYBOUND, VARIANT},
        oleauto::{
            SafeArrayCreateVector, SafeArrayDestroy, SafeArrayGetLBound, SafeArrayGetUBound,
            SysAllocStringLen, VariantInit,
        },
        winnt::{HRESULT, LONG, PVOID},
    },
};

use crate::{errors::SafeArrayError, BOOL_FALSE, BOOL_TRUE};

mod multidim;
mod serialize;

#[cfg(test)]
mod tests;

// TODO: remove when implemented in winapi
extern "system" {
    /*pub fn SafeArrayCreate(
        vt: VARTYPE,
        cDims: UINT,
        rgsabound: *mut SAFEARRAYBOUND

    ) -> *mut SAFEARRAY;*/
    /// https://docs.microsoft.com/en-us/windows/win32/api/oleauto/nf-oleauto-safearraygetelement
    pub fn SafeArrayGetElement(psa: *mut SAFEARRAY, rgIndices: *const LONG, pv: PVOID) -> HRESULT;
    /// https://docs.microsoft.com/en-us/windows/win32/api/oleauto/nf-oleauto-safearraygetvartype
    pub fn SafeArrayGetVartype(psa: *mut SAFEARRAY, pvt: *const VARTYPE) -> HRESULT;
    /// https://docs.microsoft.com/en-us/windows/win32/api/oleauto/nf-oleauto-safearrayputelement
    pub fn SafeArrayPutElement(psa: *mut SAFEARRAY, rgIndices: *const LONG, pv: PVOID) -> HRESULT;
}

/// `SafeArray` provides an ergnomic structure that allows for converting
/// `SAFEARRAY` data structures from a `VARIANT` into `Vec` or `ArrayD`. The
/// structure also destroys the `SAFEARRAY` when the `SafeArray` instance is
/// dropped.
///
/// If the `SafeArray` is converted to a `VARIANT` the memory is now owned by
/// `VARIANT` and `free_variant` should be called on the `VARIANT` to properly
/// release all the memory.
#[derive(Debug)]
pub struct SafeArray {
    psa: *mut SAFEARRAY,
    /// prevents the drop trait from actually destroying the safe array. This
    /// is in the event the array was associated with a variant.
    prevent_destroy: bool,
}

impl Drop for SafeArray {
    fn drop(&mut self) {
        if !self.prevent_destroy {
            self.destroy().unwrap();
        }
    }
}

impl SafeArray {
    /// Creates a new vector based safe array.
    pub fn new_vector(
        vt: VARTYPE,
        lower_bound: LONG,
        length: u32,
    ) -> Result<SafeArray, SafeArrayError> {
        let arr = unsafe { SafeArrayCreateVector(vt, lower_bound, length) };
        if arr.is_null() {
            Err(SafeArrayError::NullPointer)
        } else {
            trace!("allocated safe array {:?}", arr);
            Ok(SafeArray {
                psa: arr,
                prevent_destroy: false,
            })
        }
    }
    /// destroys the safe array properly, do not call this if the array was
    /// passed as an argument for a VariantArg.
    pub fn destroy(&mut self) -> Result<(), SafeArrayError> {
        if self.psa.is_null() {
            return Ok(());
        }
        unsafe {
            trace!("destroying safe array {:?}", self.psa);
            match SafeArrayDestroy(self.psa) {
                NOERROR => {
                    self.psa = ptr::null_mut();
                    Ok(())
                }
                hr => Err(SafeArrayError::from(hr)),
            }
        }
    }
    /// Reutrns the number of dimensions in the array
    pub fn dimensions_count(&self) -> Result<u16, SafeArrayError> {
        trace!("getting dimension count: {:?}", self.psa);
        unsafe {
            let r = self.psa.as_ref().ok_or(SafeArrayError::NullPointer)?;
            Ok(r.cDims)
        }
    }
    /// Gets the lower bound of the dimension, dimension index starts at 1
    pub fn dimension_lower_bound(&self, dimension: u32) -> Result<LONG, SafeArrayError> {
        trace!("getting dimension lower: {:?}", self.psa);
        unsafe {
            let mut value: LONG = 0;
            match SafeArrayGetLBound(self.psa, dimension, &mut value) {
                NOERROR => Ok(value),
                hr => Err(SafeArrayError::from(hr)),
            }
        }
    }
    /// Gets the upper bound of the dimension, dimension index starts at 1
    pub fn dimension_upper_bound(&self, dimension: u32) -> Result<LONG, SafeArrayError> {
        trace!("getting dimension upper: {:?}", self.psa);
        unsafe {
            let mut value: LONG = 0;
            match SafeArrayGetUBound(self.psa, dimension, &mut value) {
                NOERROR => Ok(value),
                hr => Err(SafeArrayError::from(hr)),
            }
        }
    }
    /// Gets all the details of the dimensions in the array.
    pub fn dimensions(&self) -> Result<Vec<SAFEARRAYBOUND>, SafeArrayError> {
        trace!("getting dimensions: {:?}", self.psa);
        unsafe {
            let r = self.psa.as_ref().ok_or(SafeArrayError::NullPointer)?;
            let mut bounds: Vec<SAFEARRAYBOUND> = Vec::with_capacity(r.cDims as usize);
            for i in 1..(r.cDims + 1) as u32 {
                let lower = self.dimension_lower_bound(i)?;
                let upper = self.dimension_upper_bound(i)?;
                bounds.push(SAFEARRAYBOUND {
                    lLbound: lower,
                    cElements: (1 + upper - lower) as ULONG,
                });
            }
            Ok(bounds)
        }
    }
    /// Gets the data type for the elements in the array
    pub fn get_vartype(&self) -> Result<VARTYPE, SafeArrayError> {
        trace!("getting var type: {:?}", self.psa);
        let mut vt: VARTYPE = VT_EMPTY as u16;
        let vt_ref: *mut VARTYPE = &mut vt;
        let result = unsafe { SafeArrayGetVartype(self.psa, vt_ref) };
        if result != NOERROR {
            return Err(SafeArrayError::from(result));
        }
        Ok(vt)
    }

    fn to_vector<R>(&self, expected_type: VARTYPE) -> Result<Vec<R>, SafeArrayError>
    where
        R: Default,
    {
        let vt = self.get_vartype()?;
        if vt != expected_type {
            return Err(SafeArrayError::IncorrectDataType(vt));
        }
        if self.dimensions_count()? != 1 {
            return Err(SafeArrayError::DimensionMismatch);
        }
        let lower = self.dimension_lower_bound(1)?;
        let upper = self.dimension_upper_bound(1)?;
        let mut result_arr: Vec<R> = Vec::with_capacity((upper - lower) as usize);
        for i in lower..=upper {
            let mut indices: [i32; 1] = [i];
            let mut v: R = R::default();
            let v_ref: *mut R = &mut v;
            let result =
                unsafe { SafeArrayGetElement(self.psa, indices.as_mut_ptr(), v_ref as PVOID) };
            if result != NOERROR {
                return Err(SafeArrayError::from(result));
            }
            result_arr.push(v);
        }
        Ok(result_arr)
    }

    fn from_vector<T>(src: &[T], vt: VARTYPE) -> Result<SafeArray, SafeArrayError> {
        let sa = SafeArray::new_vector(vt, 0, src.len() as u32)?;
        for (i, item) in src.iter().enumerate() {
            let mut indices: [i32; 1] = [i as i32];
            let v: *const T = item;
            let result = unsafe { SafeArrayPutElement(sa.psa, indices.as_mut_ptr(), v as PVOID) };
            if result != NOERROR {
                return Err(SafeArrayError::from(result));
            }
        }
        Ok(sa)
    }

    fn from_str_vector<S>(src: &[S]) -> Result<SafeArray, SafeArrayError>
    where
        S: AsRef<str>,
    {
        let sa = SafeArray::new_vector(VT_BSTR as u16, 0, src.len() as u32)?;
        for (i, item) in src.iter().enumerate() {
            let mut indices: [i32; 1] = [i as i32];
            let bstr = U16CString::from_str(item)?;
            let result = unsafe {
                let bstr_ptr = SysAllocStringLen(bstr.as_ptr(), bstr.len() as UINT);
                SafeArrayPutElement(sa.psa, indices.as_mut_ptr(), bstr_ptr as PVOID)
            };
            if result != NOERROR {
                return Err(SafeArrayError::from(result));
            }
        }
        Ok(sa)
    }

    fn to_string_vector(&self) -> Result<Vec<String>, SafeArrayError> {
        let vt = self.get_vartype()?;
        if vt != VT_BSTR as u16 {
            return Err(SafeArrayError::IncorrectDataType(vt));
        }
        if self.dimensions_count()? != 1 {
            return Err(SafeArrayError::DimensionMismatch);
        }
        let lower = self.dimension_lower_bound(1)?;
        let upper = self.dimension_upper_bound(1)?;
        let mut result_arr = Vec::with_capacity((upper - lower) as usize);
        for i in lower..=upper {
            let mut indices: [i32; 1] = [i];
            let v = unsafe {
                let mut v_ptr = ptr::null();
                let v_ptr_ptr: *mut *const u16 = &mut v_ptr;
                match SafeArrayGetElement(self.psa, indices.as_mut_ptr(), v_ptr_ptr as PVOID) {
                    NOERROR => (),
                    hr => return Err(SafeArrayError::from(hr)),
                };
                let u16_str = U16CString::from_ptr_str(v_ptr);
                u16_str.to_string()?
            };
            result_arr.push(v);
        }
        Ok(result_arr)
    }
}

impl From<*mut SAFEARRAY> for SafeArray {
    fn from(psa: *mut SAFEARRAY) -> Self {
        SafeArray {
            psa,
            prevent_destroy: false,
        }
    }
}

impl From<SafeArray> for VARIANT {
    fn from(mut sa: SafeArray) -> VARIANT {
        sa.prevent_destroy = true;
        let mut v = VARIANT::default();
        unsafe {
            VariantInit(&mut v);
            let n2 = v.n1.n2_mut();
            n2.vt = VT_SAFEARRAY as u16;
            let _val = n2.n3.parray_mut();
            *_val = sa.psa;
        }
        v
    }
}

impl TryFrom<&Vec<bool>> for SafeArray {
    type Error = SafeArrayError;

    fn try_from(val: &Vec<bool>) -> Result<Self, Self::Error> {
        let converted: Vec<i16> = val
            .iter()
            .map(|v| if *v { BOOL_TRUE } else { BOOL_FALSE })
            .collect();
        SafeArray::from_vector(&converted, VT_BOOL as u16)
    }
}

impl TryInto<Vec<bool>> for SafeArray {
    type Error = SafeArrayError;

    fn try_into(self) -> Result<Vec<bool>, Self::Error> {
        let result: Vec<i16> = self.to_vector(VT_BOOL as u16)?;
        Ok(result.iter().map(|v| *v == BOOL_TRUE).collect())
    }
}

impl TryFrom<&Vec<i16>> for SafeArray {
    type Error = SafeArrayError;

    fn try_from(value: &Vec<i16>) -> Result<Self, Self::Error> {
        SafeArray::from_vector(value, VT_I2 as u16)
    }
}

impl TryInto<Vec<i16>> for SafeArray {
    type Error = SafeArrayError;

    fn try_into(self) -> Result<Vec<i16>, Self::Error> {
        self.to_vector(VT_I2 as u16)
    }
}

impl TryFrom<&Vec<i32>> for SafeArray {
    type Error = SafeArrayError;

    fn try_from(value: &Vec<i32>) -> Result<Self, Self::Error> {
        SafeArray::from_vector(value, VT_I4 as u16)
    }
}

impl TryInto<Vec<i32>> for SafeArray {
    type Error = SafeArrayError;

    fn try_into(self) -> Result<Vec<i32>, Self::Error> {
        match self.get_vartype()? as u32 {
            VT_I4 => self.to_vector(VT_I4 as u16),
            VT_INT => self.to_vector(VT_INT as u16),
            vt => Err(SafeArrayError::IncorrectDataType(vt as u16)),
        }
    }
}

impl TryFrom<&Vec<i64>> for SafeArray {
    type Error = SafeArrayError;

    fn try_from(value: &Vec<i64>) -> Result<Self, Self::Error> {
        SafeArray::from_vector(value, VT_I8 as u16)
    }
}

impl TryInto<Vec<i64>> for SafeArray {
    type Error = SafeArrayError;

    fn try_into(self) -> Result<Vec<i64>, Self::Error> {
        self.to_vector(VT_I8 as u16)
    }
}

impl TryFrom<&Vec<f32>> for SafeArray {
    type Error = SafeArrayError;

    fn try_from(value: &Vec<f32>) -> Result<Self, Self::Error> {
        SafeArray::from_vector(value, VT_R4 as u16)
    }
}

impl TryInto<Vec<f32>> for SafeArray {
    type Error = SafeArrayError;

    fn try_into(self) -> Result<Vec<f32>, Self::Error> {
        self.to_vector(VT_R4 as u16)
    }
}

impl TryFrom<&Vec<f64>> for SafeArray {
    type Error = SafeArrayError;

    fn try_from(value: &Vec<f64>) -> Result<Self, Self::Error> {
        SafeArray::from_vector(value, VT_R8 as u16)
    }
}

impl TryInto<Vec<f64>> for SafeArray {
    type Error = SafeArrayError;

    fn try_into(self) -> Result<Vec<f64>, Self::Error> {
        self.to_vector(VT_R8 as u16)
    }
}

impl TryFrom<&Vec<u16>> for SafeArray {
    type Error = SafeArrayError;

    fn try_from(value: &Vec<u16>) -> Result<Self, Self::Error> {
        SafeArray::from_vector(value, VT_UI2 as u16)
    }
}

impl TryInto<Vec<u16>> for SafeArray {
    type Error = SafeArrayError;

    fn try_into(self) -> Result<Vec<u16>, Self::Error> {
        self.to_vector(VT_UI2 as u16)
    }
}

impl TryFrom<&Vec<u32>> for SafeArray {
    type Error = SafeArrayError;

    fn try_from(value: &Vec<u32>) -> Result<Self, Self::Error> {
        SafeArray::from_vector(value, VT_UI4 as u16)
    }
}

impl TryInto<Vec<u32>> for SafeArray {
    type Error = SafeArrayError;

    fn try_into(self) -> Result<Vec<u32>, Self::Error> {
        match self.get_vartype()? as u32 {
            VT_UI4 => self.to_vector(VT_UI4 as u16),
            VT_UINT => self.to_vector(VT_UINT as u16),
            vt => Err(SafeArrayError::IncorrectDataType(vt as u16)),
        }
    }
}

impl TryFrom<&Vec<u64>> for SafeArray {
    type Error = SafeArrayError;

    fn try_from(value: &Vec<u64>) -> Result<Self, Self::Error> {
        SafeArray::from_vector(value, VT_UI8 as u16)
    }
}

impl TryInto<Vec<u64>> for SafeArray {
    type Error = SafeArrayError;

    fn try_into(self) -> Result<Vec<u64>, Self::Error> {
        self.to_vector(VT_UI8 as u16)
    }
}

impl TryFrom<&Vec<&str>> for SafeArray {
    type Error = SafeArrayError;

    fn try_from(value: &Vec<&str>) -> Result<Self, Self::Error> {
        SafeArray::from_str_vector(value)
    }
}

impl TryFrom<&Vec<&String>> for SafeArray {
    type Error = SafeArrayError;

    fn try_from(value: &Vec<&String>) -> Result<Self, Self::Error> {
        SafeArray::from_str_vector(value)
    }
}

impl TryFrom<&Vec<String>> for SafeArray {
    type Error = SafeArrayError;

    fn try_from(value: &Vec<String>) -> Result<Self, Self::Error> {
        SafeArray::from_str_vector(value)
    }
}

impl TryInto<Vec<String>> for SafeArray {
    type Error = SafeArrayError;

    fn try_into(self) -> Result<Vec<String>, Self::Error> {
        self.to_string_vector()
    }
}