Skip to content

Commit

Permalink
Fixed derive impl on an empty enum
Browse files Browse the repository at this point in the history
  • Loading branch information
VictorKoenders committed Jan 8, 2022
1 parent db398ec commit 18aa15e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
13 changes: 11 additions & 2 deletions derive/src/derive_enum.rs
Expand Up @@ -35,6 +35,9 @@ impl DeriveEnum {
fn_body.ident_str("match");
fn_body.ident_str("self");
fn_body.group(Delimiter::Brace, |match_body| {
if self.variants.is_empty() {
self.add_empty_variant_case(match_body)?;
}
for (variant_index, variant) in self.iter_fields() {
// Self::Variant
match_body.ident_str("Self");
Expand Down Expand Up @@ -101,18 +104,24 @@ impl DeriveEnum {
?;
}
}
body.push_parsed("Ok(())")?;
Ok(())
})?;
match_body.punct(',');
}
Ok(())
})?;
fn_body.push_parsed("Ok(())")?;
Ok(())
})?;
Ok(())
}

/// If we're encoding an empty enum, we need to add an empty case in the form of:
/// `_ => core::unreachable!(),`
fn add_empty_variant_case(&self, builder: &mut StreamBuilder) -> Result {
builder.push_parsed("_ => core::unreachable!()").map(|_| ())
}

/// Build the catch-all case for an int-to-enum decode implementation
fn invalid_variant_case(&self, enum_name: &str, result: &mut StreamBuilder) -> Result {
// we'll be generating:
Expand Down Expand Up @@ -168,7 +177,7 @@ impl DeriveEnum {
// no fixed values, implement a range
variant_inner.push_parsed(format!(
"bincode::error::AllowedEnumVariants::Range {{ min: 0, max: {} }}",
self.variants.len() - 1
self.variants.len().saturating_sub(1)
))?;
}
Ok(())
Expand Down
6 changes: 6 additions & 0 deletions tests/derive.rs
Expand Up @@ -251,3 +251,9 @@ fn test_macro_newtype() {
assert_eq!(len, newtype_len);
}
}

#[derive(bincode::Encode, bincode::Decode)]
pub enum EmptyEnum {}

#[derive(bincode::Encode, bincode::BorrowDecode)]
pub enum BorrowedEmptyEnum {}

0 comments on commit 18aa15e

Please sign in to comment.