Skip to content

Commit 4c49644

Browse files
author
lifning
committed
build_const-friendly fmt::Debug for fixed-point
shows the raw hex, type, and fractional bits, in a manner that also compiles as code.
1 parent 5e5af12 commit 4c49644

File tree

1 file changed

+18
-23
lines changed

1 file changed

+18
-23
lines changed

src/fixed.rs

Lines changed: 18 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,24 @@ macro_rules! impl_common_fixed_ops {
241241
Self(self.0 >> rhs)
242242
}
243243
}
244+
245+
impl<const B: u32> core::fmt::Debug for Fixed<$t, B> {
246+
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
247+
let raw: $t = self.to_bits();
248+
write!(
249+
f,
250+
concat!(
251+
"Fixed::<",
252+
stringify!($t),
253+
",{}>::from_bits({:#x}_u32 as ",
254+
stringify!($t),
255+
")"
256+
),
257+
B, raw
258+
)
259+
}
260+
}
261+
244262
impl_trait_op_unit!($t, Not, not);
245263
impl_trait_op_self_rhs!($t, Add, add);
246264
impl_trait_op_self_rhs!($t, Sub, sub);
@@ -335,20 +353,6 @@ macro_rules! impl_signed_fixed_ops {
335353
}
336354
}
337355
impl_trait_op_unit!($t, Neg, neg);
338-
impl<const B: u32> core::fmt::Debug for Fixed<$t, B> {
339-
#[inline]
340-
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
341-
let whole: $t = self.trunc().to_bits() >> B;
342-
let fract: $t = self.fract().to_bits();
343-
let divisor: $t = 1 << B;
344-
if self.is_negative() {
345-
let whole = whole.unsigned_abs();
346-
write!(f, "-({whole}+{fract}/{divisor})")
347-
} else {
348-
write!(f, "{whole}+{fract}/{divisor}")
349-
}
350-
}
351-
}
352356
};
353357
}
354358
impl_signed_fixed_ops!(i8, u8);
@@ -393,15 +397,6 @@ macro_rules! impl_unsigned_fixed_ops {
393397
Self(self.0 & (<$t>::MAX << B))
394398
}
395399
}
396-
impl<const B: u32> core::fmt::Debug for Fixed<$t, B> {
397-
#[inline]
398-
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
399-
let whole: $t = self.trunc().to_bits() >> B;
400-
let fract: $t = self.fract().to_bits();
401-
let divisor: $t = 1 << B;
402-
write!(f, "{whole}+{fract}/{divisor}")
403-
}
404-
}
405400
};
406401
}
407402
impl_unsigned_fixed_ops!(u8);

0 commit comments

Comments
 (0)