Skip to content

Commit

Permalink
Merge pull request #89 from eiz/mack/format-options
Browse files Browse the repository at this point in the history
support formatting options in Display/Debug traits
  • Loading branch information
starkat99 committed Jun 24, 2023
2 parents aa6462e + 933531e commit 3369a17
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
20 changes: 18 additions & 2 deletions src/bfloat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -920,14 +920,14 @@ impl FromStr for bf16 {
#[cfg(not(target_arch = "spirv"))]
impl Debug for bf16 {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(f, "{:?}", self.to_f32())
Debug::fmt(&self.to_f32(), f)
}
}

#[cfg(not(target_arch = "spirv"))]
impl Display for bf16 {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(f, "{}", self.to_f32())
Display::fmt(&self.to_f32(), f)
}
}

Expand Down Expand Up @@ -1812,6 +1812,22 @@ mod test {
);
}

#[cfg(feature = "std")]
#[test]
fn formatting() {
let f = bf16::from_f32(0.1152344);

assert_eq!(format!("{:.3}", f), "0.115");
assert_eq!(format!("{:.4}", f), "0.1152");
assert_eq!(format!("{:+.4}", f), "+0.1152");
assert_eq!(format!("{:>+10.4}", f), " +0.1152");

assert_eq!(format!("{:.3?}", f), "0.115");
assert_eq!(format!("{:.4?}", f), "0.1152");
assert_eq!(format!("{:+.4?}", f), "+0.1152");
assert_eq!(format!("{:>+10.4?}", f), " +0.1152");
}

impl quickcheck::Arbitrary for bf16 {
fn arbitrary(g: &mut quickcheck::Gen) -> Self {
bf16(u16::arbitrary(g))
Expand Down
20 changes: 18 additions & 2 deletions src/binary16.rs
Original file line number Diff line number Diff line change
Expand Up @@ -930,14 +930,14 @@ impl FromStr for f16 {
#[cfg(not(target_arch = "spirv"))]
impl Debug for f16 {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(f, "{:?}", self.to_f32())
Debug::fmt(&self.to_f32(), f)
}
}

#[cfg(not(target_arch = "spirv"))]
impl Display for f16 {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(f, "{}", self.to_f32())
Display::fmt(&self.to_f32(), f)
}
}

Expand Down Expand Up @@ -1895,6 +1895,22 @@ mod test {
assert_eq!(f16::from_f32(4.) % f16::from_f32(3.), f16::from_f32(1.));
}

#[cfg(feature = "std")]
#[test]
fn formatting() {
let f = f16::from_f32(0.1152344);

assert_eq!(format!("{:.3}", f), "0.115");
assert_eq!(format!("{:.4}", f), "0.1152");
assert_eq!(format!("{:+.4}", f), "+0.1152");
assert_eq!(format!("{:>+10.4}", f), " +0.1152");

assert_eq!(format!("{:.3?}", f), "0.115");
assert_eq!(format!("{:.4?}", f), "0.1152");
assert_eq!(format!("{:+.4?}", f), "+0.1152");
assert_eq!(format!("{:>+10.4?}", f), " +0.1152");
}

impl quickcheck::Arbitrary for f16 {
fn arbitrary(g: &mut quickcheck::Gen) -> Self {
f16(u16::arbitrary(g))
Expand Down

0 comments on commit 3369a17

Please sign in to comment.