-
-
Notifications
You must be signed in to change notification settings - Fork 790
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
Help implementing data format with different null representations #1279
Comments
I would recommend not using the default Serde impls for #[derive(Serialize, Deserialize)]
struct LukeSteensen {
/* ... */
#[serde(with = "kafka::nullable")]
maybe_string: Option<String>,
#[serde(with = "kafka::nullable")]
maybe_bytes: Option<Vec<u8>>,
} The implementation would be something like: pub mod nullable {
pub trait KafkaNullable {
fn nullable_newtype() -> &'static str;
}
impl KafkaNullable for String {
fn nullable_newtype() -> &'static str { "kafka::string" }
}
// and other impls
pub fn serialize<T, S>(option: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
where
T: KafkaNullable + Serialize,
S: Serializer,
{
serializer.serialize_newtype_struct(T::nullable_newtype(), option)
}
pub fn deserialize<'de, T, D>(deserializer: D) -> Result<Option<T>, D::Error>
where
T: KafkaNullable + Deserialize<'de>,
D: Deserializer<'de>,
{
deserializer.deserialize_newtype_struct(T::nullable_newtype(), ...)
}
} The serialize_none / serialize_some / deserialize_option methods of your data format would return error unless invoked through one of these recognized kafka::nullable newtype structs. |
Got it working, thank you! To complete your example code, I added an The visitor ended up a little funky looking since it needed to "use" both the deserializer lifetime and the inner type of the optional: struct NullableVisitor<'de, T: Deserialize<'de>> {
_foo: ::std::marker::PhantomData<T>,
_bar: &'de ::std::marker::PhantomData<u8>,
} Figuring out that I needed a new Thanks again! |
I'm trying to implement a data format for the Kafka protocol but getting stuck on nullable strings and arrays:
This seems simple enough, but implies that
deserialize_option
andserialize_none
need to know about the inner type in order to know whetherlength
should bei16
ori32
. Is there some way to get this information that I'm missing?Thanks!
The text was updated successfully, but these errors were encountered: