Add PartialEq/Eq and PartialOrd/Ord to the event structs with event_ids

This commit is contained in:
Devin Ragotzy 2020-08-01 15:56:33 -04:00 committed by Jonas Platte
parent b6c289c3d2
commit 3f370c5f1b
2 changed files with 39 additions and 0 deletions

View File

@ -42,12 +42,16 @@ pub fn expand_event(input: DeriveInput) -> syn::Result<TokenStream> {
let conversion_impl = expand_from_into(&input, &kind, &var, &fields);
let eq_impl = expand_eq_ord_event(&input, &fields);
Ok(quote! {
#conversion_impl
#serialize_impl
#deserialize_impl
#eq_impl
})
}
@ -371,6 +375,37 @@ fn expand_from_into(
}
}
fn expand_eq_ord_event(input: &DeriveInput, fields: &[Field]) -> Option<TokenStream> {
if fields.iter().flat_map(|f| f.ident.as_ref()).any(|f| f == "event_id") {
let ident = &input.ident;
let (impl_gen, ty_gen, where_clause) = input.generics.split_for_impl();
Some(quote! {
impl #impl_gen ::std::cmp::PartialEq for #ident #ty_gen #where_clause {
fn eq(&self, other: &Self) -> bool {
self.event_id == other.event_id
}
}
impl #impl_gen ::std::cmp::Eq for #ident #ty_gen #where_clause {}
impl #impl_gen ::std::cmp::PartialOrd for #ident #ty_gen #where_clause {
fn partial_cmp(&self, other: &Self) -> ::std::option::Option<::std::cmp::Ordering> {
self.event_id.partial_cmp(&other.event_id)
}
}
impl #impl_gen ::std::cmp::Ord for #ident #ty_gen #where_clause {
fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {
self.event_id.cmp(&other.event_id)
}
}
})
} else {
None
}
}
/// CamelCase's a field ident like "foo_bar" to "FooBar".
fn to_camel_case(name: &Ident) -> Ident {
let span = name.span();

View File

@ -34,6 +34,10 @@ pub struct SyncEphemeralRoomEvent<C: EphemeralRoomEventContent> {
}
/// Message event.
///
/// `MessageEvent` implements the comparison trait's using only
/// the `event_id` field, a sorted list would be sorted lexicographically based on
/// the event's `EventId`.
#[derive(Clone, Debug, Event)]
pub struct MessageEvent<C: MessageEventContent> {
/// Data specific to the event type.