From e622803679e669fd9d8f11d2dc6c7466f2091eab Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Wed, 13 Jan 2021 17:47:31 +0100 Subject: [PATCH] Use bool::then to simplify some code --- crates/ruma-api-macros/src/api/parse.rs | 16 ++--- .../src/api/request/incoming.rs | 62 +++++++++---------- .../src/api/request/outgoing.rs | 8 +-- .../src/api/response/incoming.rs | 12 ++-- crates/ruma-api-macros/src/util.rs | 12 ++-- crates/ruma-events-macros/src/event.rs | 10 ++- .../ruma-events-macros/src/event_content.rs | 2 - crates/ruma-events-macros/src/event_enum.rs | 56 +++++++---------- crates/ruma-events/src/room/message.rs | 6 +- crates/ruma-state-res/src/event_auth.rs | 16 +---- crates/ruma-state-res/src/lib.rs | 9 ++- 11 files changed, 85 insertions(+), 124 deletions(-) diff --git a/crates/ruma-api-macros/src/api/parse.rs b/crates/ruma-api-macros/src/api/parse.rs index c499d3f8..b1c7db4f 100644 --- a/crates/ruma-api-macros/src/api/parse.rs +++ b/crates/ruma-api-macros/src/api/parse.rs @@ -49,15 +49,15 @@ impl Parse for Api { None }; - // TODO: Use `bool::then` when MSRV >= 1.50 - let error_ty = if input.peek(kw::error) { - let _: kw::error = input.parse()?; - let _: Token![:] = input.parse()?; + let error_ty = input + .peek(kw::error) + .then(|| { + let _: kw::error = input.parse()?; + let _: Token![:] = input.parse()?; - Some(input.parse()?) - } else { - None - }; + input.parse() + }) + .transpose()?; if let Some(req) = &request { let newtype_body_field = req.newtype_body_field(); diff --git a/crates/ruma-api-macros/src/api/request/incoming.rs b/crates/ruma-api-macros/src/api/request/incoming.rs index 1e7fe84c..b1d56c34 100644 --- a/crates/ruma-api-macros/src/api/request/incoming.rs +++ b/crates/ruma-api-macros/src/api/request/incoming.rs @@ -144,36 +144,34 @@ impl Request { (TokenStream::new(), TokenStream::new()) }; - let extract_body = if self.has_body_fields() || self.newtype_body_field().is_some() { - let body_lifetimes = if self.has_body_lifetimes() { - // duplicate the anonymous lifetime as many times as needed - let lifetimes = std::iter::repeat(quote! { '_ }).take(self.lifetimes.body.len()); - quote! { < #( #lifetimes, )* > } - } else { - TokenStream::new() - }; + let extract_body = + (self.has_body_fields() || self.newtype_body_field().is_some()).then(|| { + let body_lifetimes = self.has_body_lifetimes().then(|| { + // duplicate the anonymous lifetime as many times as needed + let lifetimes = + std::iter::repeat(quote! { '_ }).take(self.lifetimes.body.len()); + quote! { < #( #lifetimes, )* > } + }); - quote! { - let request_body: < - RequestBody #body_lifetimes - as #ruma_serde::Outgoing - >::Incoming = { - let body = ::std::convert::AsRef::<[::std::primitive::u8]>::as_ref( - request.body(), - ); + quote! { + let request_body: < + RequestBody #body_lifetimes + as #ruma_serde::Outgoing + >::Incoming = { + let body = ::std::convert::AsRef::<[::std::primitive::u8]>::as_ref( + request.body(), + ); - #serde_json::from_slice(match body { - // If the request body is completely empty, pretend it is an empty JSON - // object instead. This allows requests with only optional body parameters - // to be deserialized in that case. - [] => b"{}", - b => b, - })? - }; - } - } else { - TokenStream::new() - }; + #serde_json::from_slice(match body { + // If the request body is completely empty, pretend it is an empty JSON + // object instead. This allows requests with only optional body parameters + // to be deserialized in that case. + [] => b"{}", + b => b, + })? + }; + } + }); let (parse_body, body_vars) = if let Some(field) = self.newtype_body_field() { let field_name = field.ident.as_ref().expect("expected field to have an identifier"); @@ -194,8 +192,8 @@ impl Request { self.vars(RequestFieldKind::Body, quote!(request_body)) }; - let non_auth_impls = metadata.authentication.iter().map(|auth| { - if auth.value == "None" { + let non_auth_impls = metadata.authentication.iter().filter_map(|auth| { + (auth.value == "None").then(|| { let attrs = &auth.attrs; quote! { #( #attrs )* @@ -203,9 +201,7 @@ impl Request { #[cfg(feature = "server")] impl #ruma_api::IncomingNonAuthRequest for #incoming_request_type {} } - } else { - TokenStream::new() - } + }) }); quote! { diff --git a/crates/ruma-api-macros/src/api/request/outgoing.rs b/crates/ruma-api-macros/src/api/request/outgoing.rs index 380906b3..da363302 100644 --- a/crates/ruma-api-macros/src/api/request/outgoing.rs +++ b/crates/ruma-api-macros/src/api/request/outgoing.rs @@ -183,8 +183,8 @@ impl Request { quote! { ::default() } }; - let non_auth_impls = metadata.authentication.iter().map(|auth| { - if auth.value == "None" { + let non_auth_impls = metadata.authentication.iter().filter_map(|auth| { + (auth.value == "None").then(|| { let attrs = &auth.attrs; quote! { #( #attrs )* @@ -192,9 +192,7 @@ impl Request { #[cfg(feature = "client")] impl #lifetimes #ruma_api::OutgoingNonAuthRequest for Request #lifetimes {} } - } else { - TokenStream::new() - } + }) }); quote! { diff --git a/crates/ruma-api-macros/src/api/response/incoming.rs b/crates/ruma-api-macros/src/api/response/incoming.rs index aa6cb3a3..44aa3aa9 100644 --- a/crates/ruma-api-macros/src/api/response/incoming.rs +++ b/crates/ruma-api-macros/src/api/response/incoming.rs @@ -9,16 +9,14 @@ impl Response { let ruma_serde = quote! { #ruma_api::exports::ruma_serde }; let serde_json = quote! { #ruma_api::exports::serde_json }; - let extract_response_headers = if self.has_header_fields() { + let extract_response_headers = self.has_header_fields().then(|| { quote! { let mut headers = response.headers().clone(); } - } else { - TokenStream::new() - }; + }); let typed_response_body_decl = - if self.has_body_fields() || self.newtype_body_field().is_some() { + (self.has_body_fields() || self.newtype_body_field().is_some()).then(|| { quote! { let response_body: < ResponseBody @@ -37,9 +35,7 @@ impl Response { })? }; } - } else { - TokenStream::new() - }; + }); let response_init_fields = { let mut fields = vec![]; diff --git a/crates/ruma-api-macros/src/util.rs b/crates/ruma-api-macros/src/util.rs index 4e4a111d..78d49305 100644 --- a/crates/ruma-api-macros/src/util.rs +++ b/crates/ruma-api-macros/src/util.rs @@ -12,12 +12,12 @@ pub(crate) fn unique_lifetimes_to_tokens<'a, I: IntoIterator TokenStream { let lifetimes = lifetimes.into_iter().collect::>(); - if lifetimes.is_empty() { - TokenStream::new() - } else { - let lifetimes = quote! { #( #lifetimes ),* }; - quote! { < #lifetimes > } - } + (!lifetimes.is_empty()) + .then(|| { + let lifetimes = quote! { #( #lifetimes ),* }; + quote! { < #lifetimes > } + }) + .unwrap_or_default() } pub(crate) fn is_valid_endpoint_path(string: &str) -> bool { diff --git a/crates/ruma-events-macros/src/event.rs b/crates/ruma-events-macros/src/event.rs index 78824566..0bf7f97c 100644 --- a/crates/ruma-events-macros/src/event.rs +++ b/crates/ruma-events-macros/src/event.rs @@ -395,11 +395,11 @@ 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") { + fields.iter().flat_map(|f| f.ident.as_ref()).any(|f| f == "event_id").then(|| { let ident = &input.ident; let (impl_gen, ty_gen, where_clause) = input.generics.split_for_impl(); - Some(quote! { + quote! { #[automatically_derived] impl #impl_gen ::std::cmp::PartialEq for #ident #ty_gen #where_clause { /// This checks if two `EventId`s are equal. @@ -426,10 +426,8 @@ fn expand_eq_ord_event(input: &DeriveInput, fields: &[Field]) -> Option Self::RoomRedaction( - #ruma_events::room::redaction::SyncRedactionEvent::from(event), - ), - } - } else { - TokenStream::new() - }; + let redaction = + (*kind == EventKind::Message && *var == EventKindVariation::Full).then(|| { + quote! { + #ident::RoomRedaction(event) => Self::RoomRedaction( + #ruma_events::room::redaction::SyncRedactionEvent::from(event), + ), + } + }); Some(quote! { impl From<#ident> for #sync { @@ -274,15 +273,14 @@ fn expand_conversion_impl( let self_variants = variants.iter().map(|v| v.match_arm(quote!(Self))); let full_variants = variants.iter().map(|v| v.ctor(&full)); - let redaction = if let (EventKind::Message, EventKindVariation::Sync) = (kind, var) { - quote! { - Self::RoomRedaction(event) => { - #full::RoomRedaction(event.into_full_event(room_id)) - }, - } - } else { - TokenStream::new() - }; + let redaction = + (*kind == EventKind::Message && *var == EventKindVariation::Sync).then(|| { + quote! { + Self::RoomRedaction(event) => { + #full::RoomRedaction(event.into_full_event(room_id)) + }, + } + }); Some(quote! { #[automatically_derived] @@ -639,8 +637,8 @@ fn generate_redacted_fields( var: &EventKindVariation, is_event_kind: EventKindFn, ruma_events: &TokenStream, -) -> TokenStream { - if is_event_kind(kind, var) { +) -> Option { + is_event_kind(kind, var).then(|| { let name = Ident::new(name, Span::call_site()); if name == "unsigned" { @@ -654,9 +652,7 @@ fn generate_redacted_fields( #name: event.#name, } } - } else { - TokenStream::new() - } + }) } fn generate_custom_variant( @@ -772,7 +768,7 @@ fn accessor_methods( } }; - let prev_content = if has_prev_content_field(kind, var) { + let prev_content = has_prev_content_field(kind, var).then(|| { quote! { /// Returns the any content enum for this events prev_content. pub fn prev_content(&self) -> Option<#content_enum> { @@ -788,9 +784,7 @@ fn accessor_methods( } } } - } else { - TokenStream::new() - }; + }); Some(quote! { #[automatically_derived] @@ -956,8 +950,8 @@ fn generate_accessor( is_event_kind: EventKindFn, variants: &[EventEnumVariant], ruma_events: &TokenStream, -) -> TokenStream { - if is_event_kind(kind, var) { +) -> Option { + is_event_kind(kind, var).then(|| { let docs = format!("Returns this event's {} field.", name); let ident = Ident::new(name, Span::call_site()); let field_type = field_return_type(name, var, ruma_events); @@ -972,9 +966,7 @@ fn generate_accessor( } } } - } else { - TokenStream::new() - } + }) } fn field_return_type( diff --git a/crates/ruma-events/src/room/message.rs b/crates/ruma-events/src/room/message.rs index 976e8e3f..07d03326 100644 --- a/crates/ruma-events/src/room/message.rs +++ b/crates/ruma-events/src/room/message.rs @@ -747,11 +747,7 @@ impl FormattedBody { pulldown_cmark::html::push_html(&mut html_body, pulldown_cmark::Parser::new(body)); - if html_body == format!("

{}

\n", body) { - None - } else { - Some(Self::html(html_body)) - } + (html_body != format!("

{}

\n", body)).then(|| Self::html(html_body)) } } diff --git a/crates/ruma-state-res/src/event_auth.rs b/crates/ruma-state-res/src/event_auth.rs index 8d803dec..a6a549f7 100644 --- a/crates/ruma-state-res/src/event_auth.rs +++ b/crates/ruma-state-res/src/event_auth.rs @@ -341,24 +341,12 @@ pub fn valid_membership_change( )?; let sender_power = power_levels.users.get(user_sender).map_or_else( - || { - if sender_membership != MembershipState::Join { - None - } else { - Some(&power_levels.users_default) - } - }, + || (sender_membership == MembershipState::Join).then(|| &power_levels.users_default), // If it's okay, wrap with Some(_) Some, ); let target_power = power_levels.users.get(&target_user_id).map_or_else( - || { - if target_membership != MembershipState::Join { - None - } else { - Some(&power_levels.users_default) - } - }, + || (target_membership == MembershipState::Join).then(|| &power_levels.users_default), // If it's okay, wrap with Some(_) Some, ); diff --git a/crates/ruma-state-res/src/lib.rs b/crates/ruma-state-res/src/lib.rs index 852a12c1..d6388eb6 100644 --- a/crates/ruma-state-res/src/lib.rs +++ b/crates/ruma-state-res/src/lib.rs @@ -450,11 +450,10 @@ impl StateResolution { // The key for this is (eventType + a state_key of the signed token not sender) so // search for it let current_third_party = auth_events.iter().find_map(|(_, pdu)| { - if pdu.kind() == EventType::RoomThirdPartyInvite { - Some(pdu.clone()) // TODO no clone, auth_events is borrowed while moved - } else { - None - } + (pdu.kind() == EventType::RoomThirdPartyInvite).then(|| { + // TODO no clone, auth_events is borrowed while moved + pdu.clone() + }) }); if auth_check(