prost-wkt
prost-wkt copied to clipboard
Suggestions for oneof handling
I'm not sure exactly where to put this, but it seems relevant to this repo. I used the strum crate to help out here.
In the build script
// Don't tag oneof enums
.type_attribute(path, "#[serde(untagged)]")
// Make enum variant name serializable as lowercase
.type_attribute(path, "#[derive(::strum::Display)]")
.type_attribute(path, r#"#[strum(serialize_all = "snake_case")]"#)
// Use custom serializer and flatten
.field_attribute(
path,
r#"#[serde(flatten, serialize_with = "serialize_oneof")]"#,
)
Then in my main code:
use serde::{Serialize, Serializer, ser::SerializeMap};
use std::fmt::Display;
pub fn serialize_oneof<T, S>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
where
T: Display + serde::Serialize,
S: Serializer,
{
match value {
Some(v) => {
let mut s = serializer.serialize_map(Some(1))?;
s.serialize_entry(&format!("{}", v), v)?;
s.end()
}
None => serializer.serialize_none(),
}
}
This is an interesting solution as well. I will add it to the README as an alternative.