Skip to main content

windows_result/
ntstatus.rs

1use super::*;
2
3/// An error or status code value returned by some operating system functions.
4#[repr(transparent)]
5#[derive(Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
6#[must_use]
7pub struct NTSTATUS(pub i32);
8
9impl NTSTATUS {
10    /// Returns [`true`] if `self` is a success code.
11    #[inline]
12    pub const fn is_ok(self) -> bool {
13        self.0 >= 0
14    }
15
16    /// Returns [`true`] if `self` is a failure code.
17    #[inline]
18    pub const fn is_err(self) -> bool {
19        !self.is_ok()
20    }
21
22    /// Maps an NT error code to an HRESULT value.
23    #[inline]
24    pub const fn to_hresult(self) -> HRESULT {
25        HRESULT(if self.0 >= 0 {
26            self.0
27        } else {
28            self.0 | 0x1000_0000
29        })
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 [`NTSTATUS`] value for diagnostics.
36    #[inline]
37    #[track_caller]
38    pub fn unwrap(self) {
39        assert!(self.is_ok(), "NTSTATUS 0x{:X}", self.0);
40    }
41
42    /// Converts the [`NTSTATUS`] to [`Result<()>`][Result<_>].
43    #[inline]
44    pub fn ok(self) -> Result<()> {
45        self.to_hresult().ok()
46    }
47}
48
49impl From<NTSTATUS> for HRESULT {
50    fn from(value: NTSTATUS) -> Self {
51        value.to_hresult()
52    }
53}
54
55impl From<NTSTATUS> for Error {
56    fn from(value: NTSTATUS) -> Self {
57        value.to_hresult().into()
58    }
59}
60
61impl core::fmt::Display for NTSTATUS {
62    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
63        f.write_fmt(format_args!("{:#010X}", self.0))
64    }
65}
66
67impl core::fmt::Debug for NTSTATUS {
68    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
69        f.write_fmt(format_args!("NTSTATUS({self})"))
70    }
71}