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
use std::ptr::null_mut;
use winapi::um::oleauto::{SysAllocStringLen, SysFreeString, SysStringLen};
use widestring::U16String;
use super::errors::BStringError;
use super::ptr::Ptr;
type BSTR = *mut u16;
pub trait BStringExt {
fn allocate_bstr(&mut self) -> Result<Ptr<u16>, BStringError>;
fn allocate_managed_bstr(&mut self) -> Result<DroppableBString, BStringError>;
fn deallocate_bstr(bstr: Ptr<u16>);
fn from_bstr(bstr: *mut u16) -> U16String;
fn from_pbstr(bstr: Ptr<u16>) -> U16String;
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 cln = self.clone();
let rw = cln.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 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))
}
}
pub struct DroppableBString {
inner: Option<Ptr<u16>>
}
impl DroppableBString {
#[allow(dead_code)]
pub 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 {
fn drop(&mut self) {
match self.inner {
Some(ptr) => {
unsafe { SysFreeString(ptr.as_ptr())}
},
None => {}
}
}
}