From ea84e653ac5cfafd0329d1a013e05613009ff274 Mon Sep 17 00:00:00 2001 From: numzero Date: Mon, 16 Feb 2026 15:55:30 +0300 Subject: [PATCH] move formatting into a mod --- src/fmt.rs | 41 +++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 41 +---------------------------------------- 2 files changed, 42 insertions(+), 40 deletions(-) create mode 100644 src/fmt.rs diff --git a/src/fmt.rs b/src/fmt.rs new file mode 100644 index 0000000..292b438 --- /dev/null +++ b/src/fmt.rs @@ -0,0 +1,41 @@ +use crate::{E_BIAS, F8}; + +impl std::fmt::Binary for F8 { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if f.alternate() { + f.write_str("0b")?; + } + if self.0 == 0 { + f.write_str("0.00000p0")?; + return Ok(()); + } + let (m, e) = self.split(); + write!(f, "1.{m:05b}p{e}", e = e as i8 - E_BIAS as i8)?; + Ok(()) + } +} + +impl std::fmt::Debug for F8 { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{self:#b}f8") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_display() { + fn fmt_split(m: u8, e: u8) -> String { + let v = F8::merge(m, e); + format!("{v:b}") + } + assert_eq!("0.00000p0", fmt_split(0, 0)); + assert_eq!("1.00000p0", fmt_split(0, E_BIAS)); + assert_eq!("1.00000p1", fmt_split(0, E_BIAS + 1)); + assert_eq!("1.00000p-1", fmt_split(0, E_BIAS - 1)); + assert_eq!("1.00001p0", fmt_split(1, E_BIAS)); + assert_eq!("1.11111p0", fmt_split(0b11111, E_BIAS)); + } +} diff --git a/src/lib.rs b/src/lib.rs index fb3d5b6..823639c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ mod conv; +mod fmt; mod ops; pub const M_BITS: u8 = 5; @@ -23,43 +24,3 @@ const E_MASK: u8 = E_STORAGE_MAX << M_BITS; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] #[repr(transparent)] pub struct F8(u8); - -impl std::fmt::Binary for F8 { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - if f.alternate() { - f.write_str("0b")?; - } - if self.0 == 0 { - f.write_str("0.00000p0")?; - return Ok(()); - } - let (m, e) = self.split(); - write!(f, "1.{m:05b}p{e}", e = e as i8 - E_BIAS as i8)?; - Ok(()) - } -} - -impl std::fmt::Debug for F8 { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{self:#b}f8") - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_display() { - fn fmt_split(m: u8, e: u8) -> String { - let v = F8::merge(m, e); - format!("{v:b}") - } - assert_eq!("0.00000p0", fmt_split(0, 0)); - assert_eq!("1.00000p0", fmt_split(0, E_BIAS)); - assert_eq!("1.00000p1", fmt_split(0, E_BIAS + 1)); - assert_eq!("1.00000p-1", fmt_split(0, E_BIAS - 1)); - assert_eq!("1.00001p0", fmt_split(1, E_BIAS)); - assert_eq!("1.11111p0", fmt_split(0b11111, E_BIAS)); - } -}