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
};
// TODO: Use `bool::then` when MSRV >= 1.50
let error_ty = if input.peek(kw::error) {
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();

View File

@ -144,14 +144,14 @@ 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() {
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());
let lifetimes =
std::iter::repeat(quote! { '_ }).take(self.lifetimes.body.len());
quote! { < #( #lifetimes, )* > }
} else {
TokenStream::new()
};
});
quote! {
let request_body: <
@ -171,9 +171,7 @@ impl Request {
})?
};
}
} else {
TokenStream::new()
};
});
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! {

View File

@ -183,8 +183,8 @@ impl Request {
quote! { <T as ::std::default::Default>::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! {

View File

@ -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![];

View File

@ -12,12 +12,12 @@ pub(crate) fn unique_lifetimes_to_tokens<'a, I: IntoIterator<Item = &'a Lifetime
lifetimes: I,
) -> TokenStream {
let lifetimes = lifetimes.into_iter().collect::<BTreeSet<_>>();
if lifetimes.is_empty() {
TokenStream::new()
} else {
(!lifetimes.is_empty())
.then(|| {
let lifetimes = quote! { #( #lifetimes ),* };
quote! { < #lifetimes > }
}
})
.unwrap_or_default()
}
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> {
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<TokenStr
self.event_id.cmp(&other.event_id)
}
}
})
} else {
None
}
})
}
/// CamelCase's a field ident like "foo_bar" to "FooBar".

View File

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

View File

@ -235,15 +235,14 @@ fn expand_conversion_impl(
let ident_variants = variants.iter().map(|v| v.match_arm(&ident));
let self_variants = variants.iter().map(|v| v.ctor(quote!(Self)));
let redaction = if let (EventKind::Message, EventKindVariation::Full) = (kind, var) {
let redaction =
(*kind == EventKind::Message && *var == EventKindVariation::Full).then(|| {
quote! {
#ident::RoomRedaction(event) => Self::RoomRedaction(
#ruma_events::room::redaction::SyncRedactionEvent::from(event),
),
}
} else {
TokenStream::new()
};
});
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) {
let redaction =
(*kind == EventKind::Message && *var == EventKindVariation::Sync).then(|| {
quote! {
Self::RoomRedaction(event) => {
#full::RoomRedaction(event.into_full_event(room_id))
},
}
} else {
TokenStream::new()
};
});
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<TokenStream> {
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<TokenStream> {
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(

View File

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

View File

@ -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(