Skip to content

Commit

Permalink
add impls for fmt::Binary (#601)
Browse files Browse the repository at this point in the history
Signed-off-by: Andrew Whitehead <[email protected]>
  • Loading branch information
andrewwhitehead authored May 31, 2024
1 parent a37329e commit 5167b12
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/limb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,13 @@ impl fmt::Display for Limb {
}
}

impl fmt::Binary for Limb {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:0width$b}", &self.0, width = Self::BITS as usize)
}
}

impl fmt::LowerHex for Limb {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Expand Down
9 changes: 9 additions & 0 deletions src/uint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,15 @@ impl<const LIMBS: usize> fmt::Debug for Uint<LIMBS> {
}
}

impl<const LIMBS: usize> fmt::Binary for Uint<LIMBS> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for limb in self.limbs.iter().rev() {
fmt::Binary::fmt(limb, f)?;
}
Ok(())
}
}

impl<const LIMBS: usize> fmt::Display for Uint<LIMBS> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::UpperHex::fmt(self, f)
Expand Down
13 changes: 13 additions & 0 deletions src/uint/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,19 @@ impl fmt::Display for BoxedUint {
}
}

impl fmt::Binary for BoxedUint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.limbs.is_empty() {
return fmt::Binary::fmt(&Limb::ZERO, f);
}

for limb in self.limbs.iter().rev() {
fmt::Binary::fmt(limb, f)?;
}
Ok(())
}
}

impl fmt::LowerHex for BoxedUint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.limbs.is_empty() {
Expand Down
11 changes: 11 additions & 0 deletions src/uint/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -350,4 +350,15 @@ mod tests {
let n = U128::from_be_hex(hex);
assert_eq!(hex, format!("{:x}", n));
}

#[cfg(feature = "alloc")]
#[test]
fn fmt_binary() {
let hex = "AAAAAAAABBBBBBBBCCCCCCCCDDDDDDDD";
let n = U128::from_be_hex(hex);
let expect = "\
1010101010101010101010101010101010111011101110111011101110111011\
1100110011001100110011001100110011011101110111011101110111011101";
assert_eq!(expect, format!("{:b}", n));
}
}

0 comments on commit 5167b12

Please sign in to comment.