Skip to main content

windows_result/
hresult.rs

1use super::*;
2
3/// An error code value returned by most COM functions.
4#[repr(transparent)]
5#[derive(Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
6#[must_use]
7pub struct HRESULT(pub i32);
8
9impl HRESULT {
10    /// Creates an `HRESULT` from its severity, facility, and code, like `MAKE_HRESULT`.
11    ///
12    /// Severity is 0 for success and 1 for failure. Inputs are combined using 32-bit shifts and
13    /// bitwise OR, without masking or range validation.
14    #[doc(alias = "MAKE_HRESULT")]
15    #[inline]
16    pub const fn from_components(severity: u32, facility: u32, code: u32) -> Self {
17        Self(((severity << 31) | (facility << 16) | code) as i32)
18    }
19
20    /// Returns [`true`] if `self` is a success code.
21    #[inline]
22    pub const fn is_ok(self) -> bool {
23        self.0 >= 0
24    }
25
26    /// Returns [`true`] if `self` is a failure code.
27    #[inline]
28    pub const fn is_err(self) -> bool {
29        !self.is_ok()
30    }
31
32    /// Asserts that `self` is a success code.
33    ///
34    /// This will invoke the [`panic!`] macro if `self` is a failure code and display
35    /// the [`HRESULT`] value for diagnostics.
36    #[inline]
37    #[track_caller]
38    pub fn unwrap(self) {
39        assert!(self.is_ok(), "HRESULT 0x{:X}", self.0);
40    }
41
42    /// Converts the [`HRESULT`] to [`Result<()>`][Result<_>].
43    #[inline]
44    pub fn ok(self) -> Result<()> {
45        if self.is_ok() {
46            Ok(())
47        } else {
48            Err(self.into())
49        }
50    }
51
52    /// Calls `op` if `self` is a success code, otherwise returns [`HRESULT`]
53    /// converted to [`Result<T>`].
54    #[inline]
55    pub fn map<F, T>(self, op: F) -> Result<T>
56    where
57        F: FnOnce() -> T,
58    {
59        self.ok()?;
60        Ok(op())
61    }
62
63    /// Calls `op` if `self` is a success code, otherwise returns [`HRESULT`]
64    /// converted to [`Result<T>`].
65    #[inline]
66    pub fn and_then<F, T>(self, op: F) -> Result<T>
67    where
68        F: FnOnce() -> Result<T>,
69    {
70        self.ok()?;
71        op()
72    }
73
74    /// The error message describing the error.
75    pub fn message(self) -> String {
76        #[cfg(windows)]
77        {
78            let mut message = HeapString::default();
79            let mut code = self.0;
80            let mut module = core::ptr::null_mut();
81
82            let mut flags = FORMAT_MESSAGE_ALLOCATE_BUFFER
83                | FORMAT_MESSAGE_FROM_SYSTEM
84                | FORMAT_MESSAGE_IGNORE_INSERTS;
85
86            unsafe {
87                if self.0 & 0x1000_0000 == 0x1000_0000 {
88                    code ^= 0x1000_0000;
89                    flags |= FORMAT_MESSAGE_FROM_HMODULE;
90
91                    module = LoadLibraryExA(
92                        c"ntdll.dll".as_ptr() as _,
93                        core::ptr::null_mut(),
94                        LOAD_LIBRARY_SEARCH_DEFAULT_DIRS as u32,
95                    );
96                }
97
98                let size = FormatMessageW(
99                    flags as u32,
100                    module as _,
101                    code as _,
102                    0,
103                    &mut message.0 as *mut _ as *mut _,
104                    0,
105                    core::ptr::null(),
106                );
107
108                if !message.0.is_null() && size > 0 {
109                    String::from_utf16_lossy(wide_trim_end(core::slice::from_raw_parts(
110                        message.0,
111                        size as usize,
112                    )))
113                } else {
114                    String::default()
115                }
116            }
117        }
118
119        #[cfg(not(windows))]
120        {
121            alloc::format!("0x{:08x}", self.0 as u32)
122        }
123    }
124
125    /// Creates a new `HRESULT` from the Win32 error code returned by `GetLastError()`.
126    pub fn from_thread() -> Self {
127        #[cfg(windows)]
128        {
129            WIN32_ERROR::from_thread().into()
130        }
131        #[cfg(not(windows))]
132        {
133            unimplemented!()
134        }
135    }
136}
137
138impl<T> From<Result<T>> for HRESULT {
139    fn from(result: Result<T>) -> Self {
140        if let Err(error) = result {
141            return error.into();
142        }
143        Self(0)
144    }
145}
146
147impl core::fmt::Display for HRESULT {
148    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
149        f.write_fmt(format_args!("{:#010X}", self.0))
150    }
151}
152
153impl core::fmt::Debug for HRESULT {
154    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
155        f.write_fmt(format_args!("HRESULT({self})"))
156    }
157}