Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add discriminant derive #119

Open
RReverser opened this issue May 16, 2023 · 0 comments
Open

Add discriminant derive #119

RReverser opened this issue May 16, 2023 · 0 comments

Comments

@RReverser
Copy link

I'm often running into a case where I'd want to derive discriminant on arbitrary enums. It's even more useful nowadays now that arbitrary_enum_discriminants are stabilized in Rust, so you can customize them and not only use the default order.

For example, deriving errors with associated error codes could then look like:

use num_enum::PrimitiveDiscriminant;
use displaydoc::Display;
use thiserror::Error;

#[derive(Display, Debug, Error, PrimitiveDiscriminant)]
#[repr(u16)]
pub enum DataStoreError {
    /// data store disconnected
    Disconnect(#[source] io::Error) = 0x201,
    /// the data for key `{0}` is not available
    Redaction(String) = 0x205,
    /// invalid header (expected {expected:?}, found {found:?})
    InvalidHeader {
        expected: String,
        found: String,
    } = 0x300,
    /// unknown data store error
    Unknown = 0,
}

fn print_err(err: &DataStoreError) {
  eprintln!("Error #{:X}: {}", err.discriminant(), err);
}

This crate seems like the perfect fit for it since it has all the necessary machinery for dealing with discriminant on enums and would only need one extra trait+derive for the non-owned version of IntoPrimitive.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant