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
#![allow(clippy::upper_case_acronyms)]
#[cfg(windows)]
mod os_defs {
pub use winapi::shared::{
ntdef::{HRESULT, LPCSTR, LPCWSTR, LPSTR, LPWSTR, WCHAR},
wtypes::BSTR,
};
pub use winapi::um::combaseapi::CoTaskMemFree;
pub use winapi::um::oleauto::{SysFreeString, SysStringLen};
}
#[cfg(not(windows))]
mod os_defs {
pub type CHAR = std::os::raw::c_char;
pub type UINT = u32;
pub type WCHAR = widestring::WideChar;
pub type OLECHAR = WCHAR;
pub type LPSTR = *mut CHAR;
pub type LPWSTR = *mut WCHAR;
pub type LPCSTR = *const CHAR;
pub type LPCWSTR = *const WCHAR;
pub type BSTR = *mut OLECHAR;
pub type LPBSTR = *mut BSTR;
pub type HRESULT = i32;
fn len_ptr(p: BSTR) -> *mut UINT {
unsafe { p.cast::<UINT>().offset(-1) }
}
#[allow(non_snake_case)]
pub unsafe fn CoTaskMemFree(p: *mut libc::c_void) {
if !p.is_null() {
libc::free(p)
}
}
#[allow(non_snake_case)]
pub unsafe fn SysFreeString(p: BSTR) {
if !p.is_null() {
libc::free(len_ptr(p).cast::<_>())
}
}
#[allow(non_snake_case)]
pub unsafe fn SysStringByteLen(p: BSTR) -> UINT {
if p.is_null() {
0
} else {
*len_ptr(p)
}
}
#[allow(non_snake_case)]
pub unsafe fn SysStringLen(p: BSTR) -> UINT {
SysStringByteLen(p) / std::mem::size_of::<OLECHAR>() as UINT
}
}
pub use os_defs::*;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
#[must_use]
pub struct HRESULT(pub os_defs::HRESULT);
impl HRESULT {
pub fn is_err(&self) -> bool {
self.0 < 0
}
}
impl From<i32> for HRESULT {
fn from(v: i32) -> Self {
Self(v)
}
}
impl std::fmt::Debug for HRESULT {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
<Self as std::fmt::Display>::fmt(self, f)
}
}
impl std::fmt::Display for HRESULT {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("{:#x}", self))
}
}
impl std::fmt::LowerHex for HRESULT {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let prefix = if f.alternate() { "0x" } else { "" };
let bare_hex = format!("{:x}", self.0.abs());
f.pad_integral(self.0 >= 0, prefix, &bare_hex)
}
}