From 3f370c5f1be5d50279c1042bfa7319e341daf2b9 Mon Sep 17 00:00:00 2001 From: Devin Ragotzy Date: Sat, 1 Aug 2020 15:56:33 -0400 Subject: [PATCH] Add PartialEq/Eq and PartialOrd/Ord to the event structs with event_ids --- ruma-events-macros/src/event.rs | 35 +++++++++++++++++++++++++++++++++ ruma-events/src/event_kinds.rs | 4 ++++ 2 files changed, 39 insertions(+) diff --git a/ruma-events-macros/src/event.rs b/ruma-events-macros/src/event.rs index 1e314a5e..22fe6b41 100644 --- a/ruma-events-macros/src/event.rs +++ b/ruma-events-macros/src/event.rs @@ -42,12 +42,16 @@ pub fn expand_event(input: DeriveInput) -> syn::Result { 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 { + 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(); diff --git a/ruma-events/src/event_kinds.rs b/ruma-events/src/event_kinds.rs index 94949f85..919c73d2 100644 --- a/ruma-events/src/event_kinds.rs +++ b/ruma-events/src/event_kinds.rs @@ -34,6 +34,10 @@ pub struct SyncEphemeralRoomEvent { } /// 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 { /// Data specific to the event type.