Skip to content

Commit

Permalink
Nicer Debug impl for bitflags
Browse files Browse the repository at this point in the history
Signed-off-by: Björn Roy Baron <[email protected]>
  • Loading branch information
bjorn3 committed Dec 14, 2024
1 parent f75de34 commit 74fa39d
Showing 1 changed file with 41 additions and 1 deletion.
42 changes: 41 additions & 1 deletion src/bitflags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ macro_rules! bitflags_type {
}
) => {
$(#[$bitflags_attr])*
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[derive(Copy, Clone, PartialEq, Eq, Default)]
$vis struct $bitflags_name($bitflags_type);

impl $bitflags_name {
Expand Down Expand Up @@ -99,6 +99,46 @@ macro_rules! bitflags_type {
Self(!self.0) & Self::all()
}
}

impl core::fmt::Debug for $bitflags_name {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
const VARIANTS: &[($bitflags_name, &str)] = &[
$(($bitflags_name::$flag_name, stringify!($flag_name)),)*
];

write!(f, concat!(stringify!($bitflags_name), "("))?;
let mut first = true;
for &(val, name) in VARIANTS {
if self.contains(val) {
if !first {
write!(f, " | ")?;
}
first = false;
write!(f, "{name}")?;
}
}
write!(f, ")")
}
}
};
}
pub(crate) use bitflags_type;

#[cfg(test)]
#[allow(dead_code)]
mod tests {
super::bitflags_type! {
pub struct AccessFs: u64 {
const Execute = 1;
const WriteFile = 2;
const ReadFile = 4;
}
}

#[test]
fn debug_format() {
assert_eq!(format!("{:?}", AccessFs::EMPTY), "AccessFs()");
assert_eq!(format!("{:?}", AccessFs::all()), "AccessFs(Execute | WriteFile | ReadFile)");
assert_eq!(format!("{:?}", AccessFs::WriteFile), "AccessFs(WriteFile)");
}
}

0 comments on commit 74fa39d

Please sign in to comment.