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
use crate::{windows, Null, ValidateHandle};
use windows::{
    core::HRESULT,
    Win32::Foundation::{E_FAIL, E_HANDLE},
};

pub trait ResultExt<T> {
    /// Returns `Ok(())`, or `Err`, based on [`windows::core::Error::from_win32()`].
    fn from_win32() -> windows::core::Result<()>;

    /// Returns `Err` with [`windows::core::Error::from_win32()`].
    fn err_from_win32() -> windows::core::Result<T>;

    /// Passes a `T` through to an `Ok` value, if the check is successful, or otherwise returns `Err` with [`windows::core::Error::from_win32()`].
    ///
    /// Can be used transitionally in new cases, until this crate might offer a more suitable solution.
    fn from_checked_or_win32<F>(t: T, check: F) -> windows::core::Result<T>
    where
        F: FnOnce(&T) -> bool;

    /// Passes a `T` through to an `Ok` value, if the check is successful, or otherwise returns `Err` with [`HRESULT`](windows::core::HRESULT) [`E_FAIL`](windows::Win32::Foundation::E_FAIL).
    ///
    /// To be used with functions that don't offer an error code via `GetLastError()`.
    ///
    /// Can be used transitionally in new cases, until this crate might offer a more suitable solution.
    fn from_checked_or_e_fail<F>(t: T, check: F) -> windows::core::Result<T>
    where
        F: FnOnce(&T) -> bool;
}

impl<T> ResultExt<T> for windows::core::Result<T> {
    fn from_win32() -> windows::core::Result<()> {
        let error = windows::core::Error::from_win32();
        if error.code().is_ok() {
            Ok(())
        } else {
            Err(error)
        }
    }

    fn err_from_win32() -> windows::core::Result<T> {
        Err(windows::core::Error::from_win32())
    }

    fn from_checked_or_win32<F>(t: T, check: F) -> windows::core::Result<T>
    where
        F: FnOnce(&T) -> bool,
    {
        if check(&t) {
            Ok(t)
        } else {
            Err(windows::core::Error::from_win32())
        }
    }

    fn from_checked_or_e_fail<F>(t: T, check: F) -> windows::core::Result<T>
    where
        F: FnOnce(&T) -> bool,
    {
        if check(&t) {
            Ok(t)
        } else {
            Err(E_FAIL.into())
        }
    }
}

pub trait CheckNumberError
where
    Self: num_traits::Zero + Sized,
{
    /// Passes a non-zero `self` through to an `Ok` value, or, in case of it being zero, returns `Err` with [`windows::core::Error::from_win32()`], if it yields an error code, or `Ok(0)` otherwise.
    ///
    /// To be used with functions that communicate valid values as well as errors by a return value of 0 and need an additional call to `GetLastError()` to check whether an error has occurred (e.g., `SetWindowLongPtrW()`). Note that, depending on whether the function calls `SetLastError()` under all circumstances, you may need to precede the call for which you call this function by `SetLastError(ERROR_SUCCESS)`.
    fn nonzero_with_win32_or_err(self) -> windows::core::Result<Self>;

    /// Passes a non-zero `self` through to an `Ok` value, or, in case of it being zero, returns `Err` with [`windows::core::Error::from_win32()`].
    fn nonzero_or_win32_err(self) -> windows::core::Result<Self>;

    /// Passes a non-zero `self` through to an `Ok` value, or, in case of it being zero, returns `Err` with [`HRESULT`](windows::core::HRESULT) [`E_FAIL`](windows::Win32::Foundation::E_FAIL).
    ///
    /// To be used with functions that don't offer an error code via `GetLastError()`.
    fn nonzero_or_e_fail(self) -> windows::core::Result<Self>;
}

impl<T> CheckNumberError for T
where
    T: num_traits::Zero,
{
    fn nonzero_with_win32_or_err(self) -> windows::core::Result<Self> {
        if self.is_zero() {
            let error = windows::core::Error::from_win32();
            if error.code().is_ok() {
                Ok(self)
            } else {
                Err(error)
            }
        } else {
            Ok(self)
        }
    }

    fn nonzero_or_win32_err(self) -> windows::core::Result<Self> {
        if self.is_zero() {
            Err(windows::core::Error::from_win32())
        } else {
            Ok(self)
        }
    }

    fn nonzero_or_e_fail(self) -> windows::core::Result<Self> {
        if self.is_zero() {
            Err(E_FAIL.into())
        } else {
            Ok(self)
        }
    }
}

pub trait CheckNullError
where
    Self: Null + Sized,
{
    /// Passes a non-null `self` through to an `Ok` value, or, in case of it being null, returns `Err` with [`HRESULT`](windows::core::HRESULT) [`E_HANDLE`](windows::Win32::Foundation::E_HANDLE).
    ///
    /// To be used with functions like `CreateBitmap()` that return a handle type or null, not offering an error code via `GetLastError()`.
    fn nonnull_or_e_handle(self) -> windows::core::Result<Self>;
}

impl<T> CheckNullError for T
where
    T: Null,
{
    fn nonnull_or_e_handle(self) -> windows::core::Result<Self> {
        if self.is_null() {
            Err(E_HANDLE.into())
        } else {
            Ok(self)
        }
    }
}

pub trait CheckHandleError
where
    Self: ValidateHandle + Sized,
{
    /// Passes a `self`, if successfully validated with `is_invalid()`, through to an `Ok` value, or, in case of it being invalid, returns `Err` with [`HRESULT`](windows::core::HRESULT) [`E_HANDLE`](windows::Win32::Foundation::E_HANDLE).
    ///
    /// To be used with functions that don't offer an error code via `GetLastError()`, and when there's a need to validate with `is_invalid()`.
    fn valid_or_e_handle(self) -> windows::core::Result<Self>;
}

impl<T> CheckHandleError for T
where
    T: ValidateHandle,
{
    fn valid_or_e_handle(self) -> windows::core::Result<Self> {
        if self.is_invalid() {
            Err(E_HANDLE.into())
        } else {
            Ok(self)
        }
    }
}

pub trait HResultExt {
    /// Like [`HRESULT::ok()`](windows::core::HRESULT), but with success `HRESULT`s forwarded instead of giving `()`. Useful when working with functions that can return multiple success return values, like [`AssocQueryStringW()`][1].
    ///
    /// [1]: https://learn.microsoft.com/en-us/windows/win32/api/shlwapi/nf-shlwapi-assocquerystringw
    fn ok_with_hresult(self) -> windows::core::Result<HRESULT>;
}

impl HResultExt for HRESULT {
    fn ok_with_hresult(self) -> windows::core::Result<HRESULT> {
        if self.is_ok() {
            Ok(self)
        } else {
            Err(self.into())
        }
    }
}

#[cfg(all(test, feature = "windows_latest_compatible_all"))]
mod tests {
    use crate::{
        core::{CheckNumberError, HResultExt},
        windows,
    };
    use windows::Win32::{
        Foundation::{ERROR_INSUFFICIENT_BUFFER, E_FAIL, E_UNEXPECTED, S_FALSE, S_OK},
        Globalization::{
            GetLocaleInfoEx, LOCALE_ICURRDIGITS, LOCALE_NAME_INVARIANT, LOCALE_RETURN_NUMBER,
        },
    };

    #[test]
    fn nonzero_or_win32_err() {
        let mut two_wide_chars = [u16::MAX, u16::MAX];
        assert_eq!(
            unsafe {
                GetLocaleInfoEx(
                    LOCALE_NAME_INVARIANT,
                    LOCALE_ICURRDIGITS | LOCALE_RETURN_NUMBER,
                    Some(&mut two_wide_chars),
                )
            }
            .nonzero_or_win32_err(),
            Ok(2)
        );
        let value = unsafe { *two_wide_chars.as_ptr().cast::<u32>() };
        assert!(value <= 2); // As per docs on `LOCALE_ICURRDIGITS`.

        assert_eq!(
            unsafe {
                GetLocaleInfoEx(
                    LOCALE_NAME_INVARIANT,
                    LOCALE_ICURRDIGITS | LOCALE_RETURN_NUMBER,
                    Some(&mut [0]), // Invalid.
                )
            }
            .nonzero_or_win32_err(),
            Err(ERROR_INSUFFICIENT_BUFFER.into())
        );
    }

    #[test]
    fn hresult_ext_ok_with_hresult() {
        assert_eq!(S_OK.ok_with_hresult(), Ok(S_OK));
        assert_eq!(S_FALSE.ok_with_hresult(), Ok(S_FALSE));
        assert_eq!(E_FAIL.ok_with_hresult(), Err(E_FAIL.into()));
        assert_eq!(E_UNEXPECTED.ok_with_hresult(), Err(E_UNEXPECTED.into()));
    }
}