Skip to content

Commit 40e822b

Browse files
authored
Allow byte literals in TryFromPrimitive alternatives (#181)
Useful for when the values correspond to ascii codepoints, it's more self-explanatory to put `b'A'` than `0x41`.
1 parent 699a7ee commit 40e822b

2 files changed

Lines changed: 14 additions & 10 deletions

File tree

num_enum/tests/try_from_primitive.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -393,7 +393,7 @@ fn alternative_values() {
393393
#[repr(i8)]
394394
enum Enum {
395395
Zero = 0,
396-
#[num_enum(alternatives = [-1, 2, 3])]
396+
#[num_enum(alternatives = [-1, 2, b'\x03'])]
397397
OneTwoThreeOrMinusOne = 1,
398398
}
399399

num_enum_derive/src/parsing.rs

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -429,16 +429,20 @@ fn parse_discriminant(val_exp: &Expr) -> Result<DiscriminantValue> {
429429
unsigned_expr = expr;
430430
sign = -1;
431431
}
432-
if let Expr::Lit(ExprLit {
433-
lit: Lit::Int(ref lit_int),
434-
..
435-
}) = unsigned_expr
436-
{
437-
Ok(DiscriminantValue::Literal(
432+
match unsigned_expr {
433+
Expr::Lit(ExprLit {
434+
lit: Lit::Int(lit_int),
435+
..
436+
}) => Ok(DiscriminantValue::Literal(
438437
sign * lit_int.base10_parse::<i128>()?,
439-
))
440-
} else {
441-
Ok(DiscriminantValue::Expr(val_exp.clone()))
438+
)),
439+
Expr::Lit(ExprLit {
440+
lit: Lit::Byte(lit_byte),
441+
..
442+
}) => Ok(DiscriminantValue::Literal(
443+
sign * i128::from(lit_byte.value()),
444+
)),
445+
_ => Ok(DiscriminantValue::Expr(val_exp.clone())),
442446
}
443447
}
444448

0 commit comments

Comments
 (0)