prost
prost copied to clipboard
Implement generated enum methods via a trait instead of directly
Protobuf enums currently generate a Rust enum with an impl
block that provides methods to convert to and from a string representation of the enum variant. I would like to propose implementing these methods as the implementation of the following trait:
pub trait EnumerationUtils {
fn as_str_name(&self) -> &'static str;
fn from_str_name(value: &str) -> ::core::option::Option<Self>
where
Self: Sized;
}
Doing so allows using the trait as a bound for generic parameters so that other libraries can use them in their APIs.
My use case is an internal library that facilitates a custom version of the richer error model. At the transport level this uses a string to communicate an error code but at the library API surface I want to to use an enum generated from the servers protobuf definitions to make it type safe. For example, the library's internal prutobuf definition contains
message Error {
string code = 1;
}
but the library exposes a type
pub struct Error<C: EnumerationUtils> {
pub code: C
}
The trait bound makes to possible to do all the mapping of the generic enum to a string at the server side and vice versa on the client side.
I have a POC of this but I wanted to ask if there's interest in this change before making a PR.