Skip to content

Commit

Permalink
Avoid branch in Display match statement for empty enums (#196)
Browse files Browse the repository at this point in the history
This removes a match arm that will never be triggered for non empty
enums.
So now only if their are no arms in the enum will the code for empty
enums be generated.

This changes no functionally and is a bug fix.
  • Loading branch information
tvercruyssen authored Oct 4, 2022
1 parent 4fb92fe commit b74a780
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
7 changes: 3 additions & 4 deletions src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,8 @@ pub fn expand(input: &syn::DeriveInput, trait_name: &str) -> Result<TokenStream>
fn fmt(&self, _derive_more_display_formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
#helper_struct

match self {
match *self {
#arms
_ => Ok(()) // This is needed for empty enums
}
}
}
Expand Down Expand Up @@ -200,7 +199,7 @@ impl<'a, 'b> State<'a, 'b> {
let fields: TokenStream = (0..fields.unnamed.len())
.map(|n| {
let i = Ident::new(&format!("_{}", n), Span::call_site());
quote!(#i,)
quote!(ref #i,)
})
.collect();
quote!((#fields))
Expand All @@ -211,7 +210,7 @@ impl<'a, 'b> State<'a, 'b> {
.iter()
.map(|f| {
let i = f.ident.as_ref().unwrap();
quote!(#i,)
quote!(ref #i,)
})
.collect();
quote!({#fields})
Expand Down
7 changes: 7 additions & 0 deletions tests/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,13 @@ fn check_display() {
assert_eq!(DebugStructAsDisplay.to_string(), "DebugStructAsDisplay");
}

#[test]
fn empty_enum_impls_display() {
trait S: std::fmt::Display {}

impl S for EmptyEnum {}
}

mod generic {
#[derive(Display)]
#[display(fmt = "Generic {}", field)]
Expand Down

0 comments on commit b74a780

Please sign in to comment.