12
submitted 1 year ago* (last edited 1 year ago) by orangeboats@lemmy.world to c/rust@programming.dev

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
[-] Barbacamanitu@lemmy.world 0 points 1 year ago

So what! Who cares if it's free? Write first, profile and optimize later. Not everyone cares about whether the conversion is free. Simply matching and converting to the right integer is fast enough.

[-] orangeboats@lemmy.world 1 points 1 year ago* (last edited 1 year ago)

The reason I asked the question, was that I wanted to keep an int an int throughout the program.

It's not for performance reasons, it's just that I feel like there is a certain elegance in keeping things type safe entirely "for free" much like how Option&lt;&amp;T> is actually just a regular T*, even if it could be pointless in the big picture.

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

Rust

5966 readers
17 users here now

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

Wormhole

!performance@programming.dev

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