Skip to content

Commit 85d1aed

Browse files
committed
🎨 Improve out of bounds error
1 parent f2b7cb5 commit 85d1aed

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

src/lib.rs

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,8 @@ fn bitfield_inner(args: TokenStream, input: TokenStream) -> syn::Result<TokenStr
104104
return Err(s_err(
105105
span,
106106
format!(
107-
"The bitfield size ({bits} bits) has to be equal to the sum of its members ({offset} bits)!. \
108-
You might have to add padding (a {} bits large member prefixed with \"_\").",
107+
"The bitfield size ({bits} bits) has to be equal to the sum of its fields ({offset} bits). \
108+
You might have to add padding (a {} bits large field prefixed with \"_\").",
109109
bits - offset
110110
),
111111
));
@@ -114,7 +114,7 @@ fn bitfield_inner(args: TokenStream, input: TokenStream) -> syn::Result<TokenStr
114114
return Err(s_err(
115115
span,
116116
format!(
117-
"The size of the members ({offset} bits) is larger than the type ({bits} bits)!."
117+
"The size of the fields ({offset} bits) is larger than the type ({bits} bits)."
118118
),
119119
));
120120
}
@@ -504,6 +504,17 @@ impl ToTokens for Member {
504504
}
505505

506506
if !into.is_empty() {
507+
let (class, _) = type_info(&ty);
508+
// generate static strings for the error messages (due to const)
509+
let bounds = if class == TypeClass::SInt {
510+
let min = -((u128::MAX >> (128 - (bits - 1))) as i128) - 1;
511+
let max = u128::MAX >> (128 - (bits - 1));
512+
format!("[{}, {}]", min, max)
513+
} else {
514+
format!("[0, {}]", u128::MAX >> (128 - bits))
515+
};
516+
let bounds_error = format!("value out of bounds {bounds}");
517+
507518
tokens.extend(quote! {
508519
#doc
509520
#[doc = #location]
@@ -524,7 +535,7 @@ impl ToTokens for Member {
524535
#vis const fn #with_ident(self, value: #ty) -> Self {
525536
match self.#with_ident_checked(value) {
526537
Ok(s) => s,
527-
Err(_) => panic!("value out of bounds"),
538+
Err(_) => panic!(#bounds_error),
528539
}
529540
}
530541

0 commit comments

Comments
 (0)