From 2d6eefd622a774dfeefb8e6048f4f2a545740e4a Mon Sep 17 00:00:00 2001 From: Kamil Jarosz Date: Mon, 27 May 2024 02:00:27 +0200 Subject: [PATCH] swf: Add rounding methods to Twips --- swf/src/types/twips.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/swf/src/types/twips.rs b/swf/src/types/twips.rs index ee02365d0..d3dcc1274 100644 --- a/swf/src/types/twips.rs +++ b/swf/src/types/twips.rs @@ -130,6 +130,39 @@ impl Twips { pub fn to_pixels(self) -> f64 { f64::from(self.0) / Self::TWIPS_PER_PIXEL as f64 } + + /// Truncates this twips to a pixel. + /// + /// # Examples + /// + /// ```rust + /// use swf::Twips; + /// + /// assert_eq!(Twips::new(23).trunc_to_pixel(), Twips::new(20)); + /// assert_eq!(Twips::new(439).trunc_to_pixel(), Twips::new(420)); + /// assert_eq!(Twips::new(-47).trunc_to_pixel(), Twips::new(-40)); + /// ``` + #[inline] + pub fn trunc_to_pixel(self) -> Self { + Self::new(self.0 / Twips::TWIPS_PER_PIXEL * Twips::TWIPS_PER_PIXEL) + } + + /// Rounds this twips to the nearest pixel. + /// Rounds half-way cases to the nearest even pixel. + /// + /// # Examples + /// + /// ```rust + /// use swf::Twips; + /// + /// assert_eq!(Twips::new(29).round_to_pixel_ties_even(), Twips::new(20)); + /// assert_eq!(Twips::new(30).round_to_pixel_ties_even(), Twips::new(40)); + /// assert_eq!(Twips::new(31).round_to_pixel_ties_even(), Twips::new(40)); + /// ``` + #[inline] + pub fn round_to_pixel_ties_even(self) -> Self { + Self::from_pixels(self.to_pixels().round_ties_even()) + } } impl std::ops::Add for Twips {