prost
prost copied to clipboard
prost-build: keep protobuf's enum variant name as is
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
andCode12
in an enum, they will get conflict when converted withto_upper_camel
Would it be possible to add a configuration option, for instance, to the prost_build::Config
builder?
Yes, I think that should be possible. Sounds like a good potential feature for prost
.
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).
One thing to note.
Then we use type_attribute
function we need to set original message name from proto-file.