Parsing "open" enum fields

Apologies in advance for the rambling; I'm new to Rust and still don't know what I don't know. I'm hoping for some critique/advice for a parsing library I'm implementing for an existing binary format.

This format contains various enum-like fields, but the sets of possible values for some of them are not completely known/documented. I'd like to achieve certain goals for these fields:

  • support unknown values
  • provide type-safe names for known values
  • maintain raw values, ideally without forcing consumers to care about enums if they don't want to

I could use Option or Result with regular Enums, but this makes things awkward both for consumers who just want raw values, and for those who only care about known (named) enum values. Ideally at least the raw-value code path won't require pattern matching.

So it seems better to store the values in a generic format and let consumers "upcast" on demand. But storing values as raw integers and making consumers use something like num_enum's try_from doesn't take advantage of my knowledge about fields' types: consumers would need to specify which type of enum to convert to, which is verbose and error-prone.

That leads me to consider an API like this (rough sketch, using num_enum):

struct RawThing {

enum Thing {
    A = 1,
    B = 2,

impl RawThing {
    fn to_enum(self) -> Result<Thing, num_enum::TryFromPrimitiveError<Thing>> {

My questions:

  • Is this a reasonable design?
  • Can I reduce the boilerplate of implementing this for many such enums, perhaps with generics?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.