Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I map Result<(), E> into a numeric error code?

Tags:

rust

I have a bunch of FFI functions that I call using C. The caller expects 1 for success, or -1 on failure.

struct Error;

fn my_rust_function() -> Result<(), Error> {
    Ok(())
}

#[allow(non_snake_case)]
pub extern "C" fn Called_From_C() -> i32 {
    let result = my_rust_function();

    match result {
        Ok(_) => 1,
        Err(_) => -1,
    }
}

Is there a more idiomatic way of converting my Result<(), Error> into the 1 / -1 return code?

like image 860
TheNextman Avatar asked Jan 27 '26 22:01

TheNextman


1 Answers

I'd create an extension trait:

trait FfiError {
    fn as_c_error(&self) -> i32;
}

impl<T, E> FfiError for Result<T, E> {
    fn as_c_error(&self) -> i32 {
        match self {
            Ok(_) => 1,
            Err(_) => -1,
        }
    }
}

Once it's brought into scope, you can call it like any other method:

pub extern "C" fn called_from_c() -> i32 {
    my_rust_function().as_c_error()
}

See also:

  • Is there a way other than traits to add methods to a type I don't own?
like image 156
Shepmaster Avatar answered Jan 29 '26 11:01

Shepmaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!