12
submitted 1 year ago* (last edited 1 year ago) by [email protected] to c/[email protected]

For context: I am trying to write a Rust wrapper over a C library.

Like many C libraries, most of its functions return an int. Positive return values are meaningful (provides information) and negative values are error codes.

To give an example, think of something like int get_items_from_record(const struct record *rec, struct item *items). A positive value indicates how many items were returned. -1 could mean ErrorA, -2 ErrorB, and so on.

Since this is Rust, I want to represent this kind of integer as Result<T, E>, e.g.:

enum LibError {
    A = -1,
    B = -2,
    // ....
}

// LibResult is ideally just represented as an integer.
type LibResult = Result<NonNegativeInteger, LibError>;

// Then I can pass LibResult values back to the C code as i32 trivially.

Is there a way/crate to do this?

you are viewing a single comment's thread
view the rest of the comments
[-] [email protected] 1 points 1 year ago

Oh I see. I misunderstood the reason for wanting it represented as an int.

I'm wondering if you could just create a wrapper type that only has an int as a member, but then implement a trait on it so that it can act like a result. That, or just pass around your int type in the rust code, and when you need it to act like a result you do a conversion from int to result. Your debugger wouldn't show it as an int at that point, but it wouldn't show any other Result as an int anyway so it would br consistent with other rust code. If this still doesn't work, you could even make a struct that contains both the int and the result and keeps then synchronized. Then, when debugging, you could look into that struct and see the int value like you want.

this post was submitted on 29 Jul 2023
12 points (92.9% liked)

Rust

5772 readers
10 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

[email protected]

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 1 year ago
MODERATORS