How to obtain Prost! enum from String

824 views Asked by At

The generated enum type looks like this, although I don't really have access to the src as it's generated by Prost! during the build:

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum Fruit {
    Unspecified = 0,
    Apple = 1,
    Banana = 2,
    Lemon = 3,
    ...

I can get a &str from an enum like this:

let apple = Fruit::Apple;
assert_eq!(apple.as_str_name(), "APPLE");

This method is provided by Prost!.

But I want to get the enum from a string.

The strum crate offers a solution except I can't edit the source code file. Maybe there's a hack using include!() to attach a macro annotation during the build stage.

1

There are 1 answers

0
Joe Clay On BEST ANSWER

prost_build can be configured to attach arbitrary attributes to the generated code via type_attribute and field_attribute:

// build.rs

Config::new()
    .type_attribute("Fruit", "#[derive(EnumString)]")
    .compile_protos(["src/fruit.proto"], &["src"])
    .unwrap();