prost icon indicating copy to clipboard operation
prost copied to clipboard

prost-build: keep protobuf's enum variant name as is

Open n4to4 opened this issue 5 years ago • 3 comments

It seems that enum variant names are generated with to_upper_camel, and there is no option to customize that.

I'd like to use the same variant names both for protobuf and the generated Rust code, because

  • to serialize/deserialize the enum values to/from plain text, as well as protobuf
  • if I have two variant names like Code1_2 and Code12 in an enum, they will get conflict when converted with to_upper_camel

Would it be possible to add a configuration option, for instance, to the prost_build::Config builder?

n4to4 avatar Aug 01 '19 06:08 n4to4

Yes, I think that should be possible. Sounds like a good potential feature for prost.

danburkert avatar Jan 13 '20 01:01 danburkert

Until this https://github.com/tokio-rs/prost/pull/336 changes will be merged there is no good type safe way for casting Any to concrete message. I have workaround like this:


/* test.proto
syntax = "proto3";
package proto3.test;

message DNAExample {
  uint32 uint = 1;
  string str = 2;
}
*/

pub mod protobuf {
  include!(concat!(env!("OUT_DIR"), "/protoapi.rs"));

  #[derive(Clone, PartialEq, ::prost::Message)]
  pub struct DnaExample {
      #[prost(uint32, tag="1")]
      pub uint: u32,
      #[prost(string, tag="2")]
      pub str: ::prost::alloc::string::String,
  }
}

#[macro_export]
macro_rules! cast_any {
[$castin_type:ident] => {
    |attr: &prost_types::Any| {
    use prost::{Message, bytes::Bytes};

      let type_url =
        format!("type.googleapis.com/test.{}", stringify!($castin_type));
      if attr.type_url == type_url {
        let value = protobuf::$castin_type::decode(Bytes::from(attr.value.clone()));
        Some(value)
      } else {
        None
      }
    }
  };
}

fn main() {
  // type.googleapis.com/test.DNAMessage != type.googleapis.com/test.DnaMessage
  let attr = cast_any![DnaExample](&any_message); // None
}

But it doesn't work correctly all the time because protobuf messages are renamed by default during codegen process as @n4to4 has mentioned above in subject (enum, struct).

Voronar avatar Apr 23 '21 13:04 Voronar

One thing to note. Then we use type_attribute function we need to set original message name from proto-file.

Voronar avatar Apr 26 '21 14:04 Voronar