Allow byte literals as enum discriminants in CheckedBitPattern derive macro. (#155)

This commit is contained in:
zachs18 2022-12-29 18:23:14 -06:00 committed by GitHub
parent a758c0956e
commit dbb776d443
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 0 deletions

View File

@ -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"),
}
}

View File

@ -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 {
@ -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];