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

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

Open
n4to4 opened this issue Aug 1, 2019 · 3 comments
Open

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

n4to4 opened this issue Aug 1, 2019 · 3 comments

Comments

@n4to4
Copy link

n4to4 commented Aug 1, 2019

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?

@danburkert
Copy link
Collaborator

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

@Voronar
Copy link

Voronar commented Apr 23, 2021

Until this #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
Copy link

Voronar commented Apr 26, 2021

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

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

3 participants