rust/bits: Use checked_ilog2() in Binary::format to avoid panic
ilog2() panics when VALID__ is 0 on empty bits. Switch to checked_ilog2() to handle zero safely. Signed-off-by: Nguyen Dinh Phi <phind.uet@gmail.com> Link: https://lore.kernel.org/r/20260802170346.3493821-3-phind.uet@gmail.com Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
Nguyen Dinh Phi committed
Aug 3, 2026 at 01:03 UTC
e27a401d2e5a78a303f2c393a289638824e8c0a7
1 file changed
+14
-1
rust/bits/src/lib.rs
+14
-1
@@ -215,7 +215,9 @@ macro_rules! bits {
215
impl ::std::fmt::Binary for $struct_name {
216
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
217
// If no width, use the highest valid bit
218
- let width = f.width().unwrap_or((Self::VALID__.ilog2() + 1) as usize);
218
+ let width = f
219
+ .width()
220
+ .unwrap_or(Self::VALID__.checked_ilog2().map_or(1, |bit| (bit + 1) as usize));
221
write!(f, "{:0>width$.precision$b}", self.0,
222
width = width,
223
precision = f.precision().unwrap_or(width))
@@ -412,6 +414,12 @@ mod test {
414
}
415
}
416
417
+ bits! {
418
+ pub struct EmptyMask(u32) {
419
+ NONE = 0,
420
+ }
421
+ }
422
+
423
#[test]
424
pub fn test_not() {
425
assert_eq!(
@@ -450,4 +458,9 @@ mod test {
458
op1 -= InterruptMask::RI;
459
assert_eq!(op1, InterruptMask::E - InterruptMask::RI);
460
}
461
+
462
+ #[test]
463
+ pub fn test_bit_display_empty() {
464
+ assert_eq!(format!("{:b}", EmptyMask::NONE), "0");
465
+ }
466
}