Search code examples
rustffisignedness

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?


Solution

  • 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: