events: Raise an error when trying to serialize _Custom variant of event content enum

This commit is contained in:
Jonas Platte 2022-01-17 00:43:00 +01:00
parent ef6728abde
commit e387abda81
No known key found for this signature in database
GPG Key ID: 7D261D771D915378
2 changed files with 18 additions and 2 deletions

View File

@ -303,6 +303,9 @@ fn expand_content_enum(
let marker_trait_impl = expand_marker_trait_impl(kind, ruma_events); let marker_trait_impl = expand_marker_trait_impl(kind, ruma_events);
let from_impl = expand_from_impl(&ident, &content, variants); let from_impl = expand_from_impl(&ident, &content, variants);
let serialize_custom_event_error_path =
quote! { #ruma_events::serialize_custom_event_error }.to_string();
quote! { quote! {
#( #attrs )* #( #attrs )*
#[derive(Clone, Debug, #serde::Serialize)] #[derive(Clone, Debug, #serde::Serialize)]
@ -315,8 +318,8 @@ fn expand_content_enum(
#variant_decls(#content), #variant_decls(#content),
)* )*
#[doc(hidden)] #[doc(hidden)]
#[serde(serialize_with = #serialize_custom_event_error_path)]
_Custom { _Custom {
#[serde(skip)]
event_type: ::std::string::String, event_type: ::std::string::String,
}, },
} }

View File

@ -121,7 +121,7 @@ use ruma_identifiers::{EventEncryptionAlgorithm, RoomVersionId};
use ruma_serde::Raw; use ruma_serde::Raw;
use serde::{ use serde::{
de::{self, IgnoredAny}, de::{self, IgnoredAny},
Deserialize, Serialize, Deserialize, Serialize, Serializer,
}; };
use serde_json::value::RawValue as RawJsonValue; use serde_json::value::RawValue as RawJsonValue;
@ -406,3 +406,16 @@ where
#[doc(hidden)] #[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PrivOwnedStr(Box<str>); pub struct PrivOwnedStr(Box<str>);
/// Helper function for erroring when trying to serialize an event enum _Custom
/// variant that can only be created by deserializing from an unknown event
/// type.
#[doc(hidden)]
#[allow(clippy::ptr_arg)]
fn serialize_custom_event_error<S: Serializer>(_: &String, _: S) -> Result<S::Ok, S::Error> {
Err(serde::ser::Error::custom(
"Failed to serialize event [content] enum: Unknown event type.\n\
To send custom events, turn them into `Raw<EnumType>` by going through
`serde_json::value::to_raw_value` and `Raw::from_json`.",
))
}