Skip to content

Commit

Permalink
Allow byte literals as enum discriminants in CheckedBitPattern derive…
Browse files Browse the repository at this point in the history
… macro. (#155)
  • Loading branch information
zachs18 authored Dec 30, 2022
1 parent a758c09 commit dbb776d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
1 change: 1 addition & 0 deletions derive/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -766,6 +766,7 @@ fn parse_int_expr(expr: &Expr) -> Result<i64> {
parse_int_expr(expr).map(|int| -int)
}
Expr::Lit(ExprLit { lit: Lit::Int(int), .. }) => int.base10_parse(),
Expr::Lit(ExprLit { lit: Lit::Byte(byte), .. }) => Ok(byte.value().into()),
_ => bail!("Not an integer expression"),
}
}
23 changes: 23 additions & 0 deletions derive/tests/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,16 @@ enum CheckedBitPatternEnumNonContiguous {
E = 56,
}

#[repr(u8)]
#[derive(Debug, Clone, Copy, NoUninit, CheckedBitPattern, PartialEq, Eq)]
enum CheckedBitPatternEnumByteLit {
A = b'A',
B = b'B',
C = b'C',
D = b'D',
E = b'E',
}

#[derive(Debug, Copy, Clone, NoUninit, CheckedBitPattern, PartialEq, Eq)]
#[repr(C)]
struct CheckedBitPatternStruct {
Expand Down Expand Up @@ -187,6 +197,19 @@ fn passes_cast_noncontiguous() {
assert_eq!(*res, CheckedBitPatternEnumNonContiguous::E);
}

#[test]
fn fails_cast_bytelit() {
let can_cast = CheckedBitPatternEnumByteLit::is_valid_bit_pattern(&b'a');
assert!(!can_cast);
}

#[test]
fn passes_cast_bytelit() {
let res =
bytemuck::checked::cast_slice::<u8, CheckedBitPatternEnumByteLit>(b"CAB");
assert_eq!(res, [CheckedBitPatternEnumByteLit::C, CheckedBitPatternEnumByteLit::A, CheckedBitPatternEnumByteLit::B]);
}

#[test]
fn fails_cast_struct() {
let pod = [0u8, 24u8];
Expand Down

0 comments on commit dbb776d

Please sign in to comment.