Skip to content

Commit

Permalink
ntstatus unwrap
Browse files Browse the repository at this point in the history
  • Loading branch information
kennykerr committed Oct 15, 2024
1 parent 47e2228 commit b941a99
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 0 deletions.
11 changes: 11 additions & 0 deletions crates/libs/windows/src/extensions/Win32/Foundation/NTSTATUS.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,23 @@ impl NTSTATUS {
pub const fn is_ok(self) -> bool {
self.0 >= 0
}

#[inline]
pub const fn is_err(self) -> bool {
!self.is_ok()
}

#[inline]
pub const fn to_hresult(self) -> windows_core::HRESULT {
windows_core::HRESULT::from_nt(self.0)
}

#[inline]
#[track_caller]
pub fn unwrap(self) {
assert!(self.is_ok(), "NTSTATUS 0x{:X}", self.0);
}

#[inline]
pub fn ok(self) -> windows_core::Result<()> {
if self.is_ok() {
Expand All @@ -22,11 +31,13 @@ impl NTSTATUS {
}
}
}

impl From<NTSTATUS> for windows_core::HRESULT {
fn from(value: NTSTATUS) -> Self {
value.to_hresult()
}
}

impl From<NTSTATUS> for windows_core::Error {
fn from(value: NTSTATUS) -> Self {
value.to_hresult().into()
Expand Down
6 changes: 6 additions & 0 deletions crates/tests/misc/result/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ publish = false
doc = false
doctest = false

[dependencies.windows]
workspace = true
features = [
"Win32_Foundation",
]

[dependencies.windows-result]
workspace = true

Expand Down
68 changes: 68 additions & 0 deletions crates/tests/misc/result/tests/ntstatus.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
use windows::Win32::Foundation::{NTSTATUS, STATUS_INVALID_ACL, STATUS_SUCCESS, S_OK};
use windows_result::Result as WindowsResult;
use windows_result::HRESULT;

#[test]
fn test() {
assert!(STATUS_SUCCESS.is_ok());
assert!(!STATUS_INVALID_ACL.is_ok());

assert!(!STATUS_SUCCESS.is_err());
assert!(STATUS_INVALID_ACL.is_err());

STATUS_SUCCESS.unwrap();
let result: WindowsResult<()> = STATUS_SUCCESS.ok();
assert!(result.is_ok());

assert_eq!(STATUS_SUCCESS.to_hresult(), S_OK);

// Tests convertibility.
a().unwrap();
b().unwrap();
}

#[test]
#[should_panic(expected = "NTSTATUS 0xC0000077")]
fn test_panic() {
STATUS_INVALID_ACL.unwrap();
}

fn a() -> WindowsResult<()> {
fn a() -> WindowsResult<()> {
Ok(())
}

fn b() -> Result<(), HRESULT> {
Ok(())
}

fn c() -> Result<(), NTSTATUS> {
Ok(())
}

a()?;
b()?;
c()?;

Ok(())
}

fn b() -> Result<(), HRESULT> {
fn a() -> WindowsResult<()> {
Ok(())
}

fn b() -> Result<(), HRESULT> {
Ok(())
}

fn c() -> Result<(), NTSTATUS> {
Ok(())
}

a()?;
b()?;
c()?;

Ok(())
}

0 comments on commit b941a99

Please sign in to comment.