TheNextman
TheNextman

Reputation: 12566

How do I represent C's "unsigned negative" values in Rust code?

I'm calling the ResumeThread WinAPI function from Rust, using the winapi crate.

The documentation says:

If the function succeeds, the return value is the thread's previous suspend count.

If the function fails, the return value is (DWORD) -1.

How can I effectively check if there was an error?

In C:

if (ResumeThread(hMyThread) == (DWORD) -1) {
    // There was an error....
}

In Rust:

unsafe {
    if ResumeThread(my_thread) == -1 {
            // There was an error....
    }
}
the trait `std::ops::Neg` is not implemented for `u32`

I understand the error; but what is the best way to be semantically the same as the C code? Check against std::u32::MAX?

Upvotes: 2

Views: 520

Answers (2)

Shepmaster
Shepmaster

Reputation: 430574

In C, (type) expression is called a type cast. In Rust, you can perform a type cast by using the as keyword. We also give the literal an explicit type:

if ResumeThread(my_thread) == -1i32 as u32 {
    // There was an error....
}

I would personally use std::u32::MAX, potentially renamed, as they are the same value:

use std::u32::MAX as ERROR_VAL;

if ResumeThread(my_thread) == ERROR_VAL {
    // There was an error....
}

See also:

Upvotes: 7

hobbs
hobbs

Reputation: 239791

Yes, either std::u32::MAX or perhaps !0u32 (the equivalent of C ~0UL, which emphasizes the fact that it's the all-bits-set value for the given type).

Upvotes: 3

Related Questions