Use bool::then to simplify some code

This commit is contained in:
Jonas Platte 2021-01-13 17:47:31 +01:00
parent 7fbb0ade77
commit e622803679
No known key found for this signature in database
GPG Key ID: CC154DE0E30B7C67
11 changed files with 85 additions and 124 deletions

View File

@ -49,15 +49,15 @@ impl Parse for Api {
None None
}; };
// TODO: Use `bool::then` when MSRV >= 1.50 let error_ty = input
let error_ty = if input.peek(kw::error) { .peek(kw::error)
let _: kw::error = input.parse()?; .then(|| {
let _: Token![:] = input.parse()?; let _: kw::error = input.parse()?;
let _: Token![:] = input.parse()?;
Some(input.parse()?) input.parse()
} else { })
None .transpose()?;
};
if let Some(req) = &request { if let Some(req) = &request {
let newtype_body_field = req.newtype_body_field(); let newtype_body_field = req.newtype_body_field();

View File

@ -144,36 +144,34 @@ impl Request {
(TokenStream::new(), TokenStream::new()) (TokenStream::new(), TokenStream::new())
}; };
let extract_body = if self.has_body_fields() || self.newtype_body_field().is_some() { let extract_body =
let body_lifetimes = if self.has_body_lifetimes() { (self.has_body_fields() || self.newtype_body_field().is_some()).then(|| {
// duplicate the anonymous lifetime as many times as needed let body_lifetimes = self.has_body_lifetimes().then(|| {
let lifetimes = std::iter::repeat(quote! { '_ }).take(self.lifetimes.body.len()); // duplicate the anonymous lifetime as many times as needed
quote! { < #( #lifetimes, )* > } let lifetimes =
} else { std::iter::repeat(quote! { '_ }).take(self.lifetimes.body.len());
TokenStream::new() quote! { < #( #lifetimes, )* > }
}; });
quote! { quote! {
let request_body: < let request_body: <
RequestBody #body_lifetimes RequestBody #body_lifetimes
as #ruma_serde::Outgoing as #ruma_serde::Outgoing
>::Incoming = { >::Incoming = {
let body = ::std::convert::AsRef::<[::std::primitive::u8]>::as_ref( let body = ::std::convert::AsRef::<[::std::primitive::u8]>::as_ref(
request.body(), request.body(),
); );
#serde_json::from_slice(match body { #serde_json::from_slice(match body {
// If the request body is completely empty, pretend it is an empty JSON // If the request body is completely empty, pretend it is an empty JSON
// object instead. This allows requests with only optional body parameters // object instead. This allows requests with only optional body parameters
// to be deserialized in that case. // to be deserialized in that case.
[] => b"{}", [] => b"{}",
b => b, b => b,
})? })?
}; };
} }
} else { });
TokenStream::new()
};
let (parse_body, body_vars) = if let Some(field) = self.newtype_body_field() { 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"); 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)) self.vars(RequestFieldKind::Body, quote!(request_body))
}; };
let non_auth_impls = metadata.authentication.iter().map(|auth| { let non_auth_impls = metadata.authentication.iter().filter_map(|auth| {
if auth.value == "None" { (auth.value == "None").then(|| {
let attrs = &auth.attrs; let attrs = &auth.attrs;
quote! { quote! {
#( #attrs )* #( #attrs )*
@ -203,9 +201,7 @@ impl Request {
#[cfg(feature = "server")] #[cfg(feature = "server")]
impl #ruma_api::IncomingNonAuthRequest for #incoming_request_type {} impl #ruma_api::IncomingNonAuthRequest for #incoming_request_type {}
} }
} else { })
TokenStream::new()
}
}); });
quote! { quote! {

View File

@ -183,8 +183,8 @@ impl Request {
quote! { <T as ::std::default::Default>::default() } quote! { <T as ::std::default::Default>::default() }
}; };
let non_auth_impls = metadata.authentication.iter().map(|auth| { let non_auth_impls = metadata.authentication.iter().filter_map(|auth| {
if auth.value == "None" { (auth.value == "None").then(|| {
let attrs = &auth.attrs; let attrs = &auth.attrs;
quote! { quote! {
#( #attrs )* #( #attrs )*
@ -192,9 +192,7 @@ impl Request {
#[cfg(feature = "client")] #[cfg(feature = "client")]
impl #lifetimes #ruma_api::OutgoingNonAuthRequest for Request #lifetimes {} impl #lifetimes #ruma_api::OutgoingNonAuthRequest for Request #lifetimes {}
} }
} else { })
TokenStream::new()
}
}); });
quote! { quote! {

View File

@ -9,16 +9,14 @@ impl Response {
let ruma_serde = quote! { #ruma_api::exports::ruma_serde }; let ruma_serde = quote! { #ruma_api::exports::ruma_serde };
let serde_json = quote! { #ruma_api::exports::serde_json }; 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! { quote! {
let mut headers = response.headers().clone(); let mut headers = response.headers().clone();
} }
} else { });
TokenStream::new()
};
let typed_response_body_decl = 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! { quote! {
let response_body: < let response_body: <
ResponseBody ResponseBody
@ -37,9 +35,7 @@ impl Response {
})? })?
}; };
} }
} else { });
TokenStream::new()
};
let response_init_fields = { let response_init_fields = {
let mut fields = vec![]; let mut fields = vec![];

View File

@ -12,12 +12,12 @@ pub(crate) fn unique_lifetimes_to_tokens<'a, I: IntoIterator<Item = &'a Lifetime
lifetimes: I, lifetimes: I,
) -> TokenStream { ) -> TokenStream {
let lifetimes = lifetimes.into_iter().collect::<BTreeSet<_>>(); let lifetimes = lifetimes.into_iter().collect::<BTreeSet<_>>();
if lifetimes.is_empty() { (!lifetimes.is_empty())
TokenStream::new() .then(|| {
} else { let lifetimes = quote! { #( #lifetimes ),* };
let lifetimes = quote! { #( #lifetimes ),* }; quote! { < #lifetimes > }
quote! { < #lifetimes > } })
} .unwrap_or_default()
} }
pub(crate) fn is_valid_endpoint_path(string: &str) -> bool { pub(crate) fn is_valid_endpoint_path(string: &str) -> bool {

View File

@ -395,11 +395,11 @@ fn expand_from_into(
} }
fn expand_eq_ord_event(input: &DeriveInput, fields: &[Field]) -> Option<TokenStream> { 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") { fields.iter().flat_map(|f| f.ident.as_ref()).any(|f| f == "event_id").then(|| {
let ident = &input.ident; let ident = &input.ident;
let (impl_gen, ty_gen, where_clause) = input.generics.split_for_impl(); let (impl_gen, ty_gen, where_clause) = input.generics.split_for_impl();
Some(quote! { quote! {
#[automatically_derived] #[automatically_derived]
impl #impl_gen ::std::cmp::PartialEq for #ident #ty_gen #where_clause { impl #impl_gen ::std::cmp::PartialEq for #ident #ty_gen #where_clause {
/// This checks if two `EventId`s are equal. /// This checks if two `EventId`s are equal.
@ -426,10 +426,8 @@ fn expand_eq_ord_event(input: &DeriveInput, fields: &[Field]) -> Option<TokenStr
self.event_id.cmp(&other.event_id) self.event_id.cmp(&other.event_id)
} }
} }
}) }
} else { })
None
}
} }
/// CamelCase's a field ident like "foo_bar" to "FooBar". /// CamelCase's a field ident like "foo_bar" to "FooBar".

View File

@ -275,9 +275,7 @@ pub fn expand_event_content(
Ok(quote! { Ok(quote! {
#event_content #event_content
#event_content_derive #event_content_derive
#redacted #redacted
}) })
} }

View File

@ -235,15 +235,14 @@ fn expand_conversion_impl(
let ident_variants = variants.iter().map(|v| v.match_arm(&ident)); let ident_variants = variants.iter().map(|v| v.match_arm(&ident));
let self_variants = variants.iter().map(|v| v.ctor(quote!(Self))); let self_variants = variants.iter().map(|v| v.ctor(quote!(Self)));
let redaction = if let (EventKind::Message, EventKindVariation::Full) = (kind, var) { let redaction =
quote! { (*kind == EventKind::Message && *var == EventKindVariation::Full).then(|| {
#ident::RoomRedaction(event) => Self::RoomRedaction( quote! {
#ruma_events::room::redaction::SyncRedactionEvent::from(event), #ident::RoomRedaction(event) => Self::RoomRedaction(
), #ruma_events::room::redaction::SyncRedactionEvent::from(event),
} ),
} else { }
TokenStream::new() });
};
Some(quote! { Some(quote! {
impl From<#ident> for #sync { 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 self_variants = variants.iter().map(|v| v.match_arm(quote!(Self)));
let full_variants = variants.iter().map(|v| v.ctor(&full)); let full_variants = variants.iter().map(|v| v.ctor(&full));
let redaction = if let (EventKind::Message, EventKindVariation::Sync) = (kind, var) { let redaction =
quote! { (*kind == EventKind::Message && *var == EventKindVariation::Sync).then(|| {
Self::RoomRedaction(event) => { quote! {
#full::RoomRedaction(event.into_full_event(room_id)) Self::RoomRedaction(event) => {
}, #full::RoomRedaction(event.into_full_event(room_id))
} },
} else { }
TokenStream::new() });
};
Some(quote! { Some(quote! {
#[automatically_derived] #[automatically_derived]
@ -639,8 +637,8 @@ fn generate_redacted_fields(
var: &EventKindVariation, var: &EventKindVariation,
is_event_kind: EventKindFn, is_event_kind: EventKindFn,
ruma_events: &TokenStream, ruma_events: &TokenStream,
) -> TokenStream { ) -> Option<TokenStream> {
if is_event_kind(kind, var) { is_event_kind(kind, var).then(|| {
let name = Ident::new(name, Span::call_site()); let name = Ident::new(name, Span::call_site());
if name == "unsigned" { if name == "unsigned" {
@ -654,9 +652,7 @@ fn generate_redacted_fields(
#name: event.#name, #name: event.#name,
} }
} }
} else { })
TokenStream::new()
}
} }
fn generate_custom_variant( 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! { quote! {
/// Returns the any content enum for this events prev_content. /// Returns the any content enum for this events prev_content.
pub fn prev_content(&self) -> Option<#content_enum> { pub fn prev_content(&self) -> Option<#content_enum> {
@ -788,9 +784,7 @@ fn accessor_methods(
} }
} }
} }
} else { });
TokenStream::new()
};
Some(quote! { Some(quote! {
#[automatically_derived] #[automatically_derived]
@ -956,8 +950,8 @@ fn generate_accessor(
is_event_kind: EventKindFn, is_event_kind: EventKindFn,
variants: &[EventEnumVariant], variants: &[EventEnumVariant],
ruma_events: &TokenStream, ruma_events: &TokenStream,
) -> TokenStream { ) -> Option<TokenStream> {
if is_event_kind(kind, var) { is_event_kind(kind, var).then(|| {
let docs = format!("Returns this event's {} field.", name); let docs = format!("Returns this event's {} field.", name);
let ident = Ident::new(name, Span::call_site()); let ident = Ident::new(name, Span::call_site());
let field_type = field_return_type(name, var, ruma_events); let field_type = field_return_type(name, var, ruma_events);
@ -972,9 +966,7 @@ fn generate_accessor(
} }
} }
} }
} else { })
TokenStream::new()
}
} }
fn field_return_type( fn field_return_type(

View File

@ -747,11 +747,7 @@ impl FormattedBody {
pulldown_cmark::html::push_html(&mut html_body, pulldown_cmark::Parser::new(body)); pulldown_cmark::html::push_html(&mut html_body, pulldown_cmark::Parser::new(body));
if html_body == format!("<p>{}</p>\n", body) { (html_body != format!("<p>{}</p>\n", body)).then(|| Self::html(html_body))
None
} else {
Some(Self::html(html_body))
}
} }
} }

View File

@ -341,24 +341,12 @@ pub fn valid_membership_change<E: Event>(
)?; )?;
let sender_power = power_levels.users.get(user_sender).map_or_else( let sender_power = power_levels.users.get(user_sender).map_or_else(
|| { || (sender_membership == MembershipState::Join).then(|| &power_levels.users_default),
if sender_membership != MembershipState::Join {
None
} else {
Some(&power_levels.users_default)
}
},
// If it's okay, wrap with Some(_) // If it's okay, wrap with Some(_)
Some, Some,
); );
let target_power = power_levels.users.get(&target_user_id).map_or_else( let target_power = power_levels.users.get(&target_user_id).map_or_else(
|| { || (target_membership == MembershipState::Join).then(|| &power_levels.users_default),
if target_membership != MembershipState::Join {
None
} else {
Some(&power_levels.users_default)
}
},
// If it's okay, wrap with Some(_) // If it's okay, wrap with Some(_)
Some, Some,
); );

View File

@ -450,11 +450,10 @@ impl StateResolution {
// The key for this is (eventType + a state_key of the signed token not sender) so // The key for this is (eventType + a state_key of the signed token not sender) so
// search for it // search for it
let current_third_party = auth_events.iter().find_map(|(_, pdu)| { let current_third_party = auth_events.iter().find_map(|(_, pdu)| {
if pdu.kind() == EventType::RoomThirdPartyInvite { (pdu.kind() == EventType::RoomThirdPartyInvite).then(|| {
Some(pdu.clone()) // TODO no clone, auth_events is borrowed while moved // TODO no clone, auth_events is borrowed while moved
} else { pdu.clone()
None })
}
}); });
if auth_check( if auth_check(