[librsvg] unit_interval: add constructor that clamps a f64



commit f08dad599ad32f4b1b5443d1cdf4173cef22bcbc
Author: Paolo Borelli <pborelli gnome org>
Date:   Sun Dec 30 14:53:41 2018 +0100

    unit_interval: add constructor that clamps a f64
    
    Also derive PartialOrd and remove default to 1.0, since that made
    sense for opacity, but it is misleading for other uses. Beside it
    is not used anywhere.

 rsvg_internals/src/unit_interval.rs | 28 +++++++++++++++-------------
 1 file changed, 15 insertions(+), 13 deletions(-)
---
diff --git a/rsvg_internals/src/unit_interval.rs b/rsvg_internals/src/unit_interval.rs
index a4973044..861f293d 100644
--- a/rsvg_internals/src/unit_interval.rs
+++ b/rsvg_internals/src/unit_interval.rs
@@ -2,13 +2,14 @@ use cssparser::Parser;
 
 use error::*;
 use parsers::{CssParserExt, Parse, ParseError};
+use util;
 
-#[derive(Debug, Copy, Clone, PartialEq)]
+#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
 pub struct UnitInterval(pub f64);
 
-impl Default for UnitInterval {
-    fn default() -> UnitInterval {
-        UnitInterval(1.0)
+impl UnitInterval {
+    pub fn clamp(val: f64) -> UnitInterval {
+        UnitInterval(util::clamp(val, 0.0, 1.0))
     }
 }
 
@@ -23,15 +24,7 @@ impl Parse for UnitInterval {
                 .map_err(|_| ValueErrorKind::Parse(ParseError::new("expected number")))?,
         );
 
-        let cx = if x < 0.0 {
-            0.0
-        } else if x > 1.0 {
-            1.0
-        } else {
-            x
-        };
-
-        Ok(UnitInterval(cx))
+        Ok(UnitInterval::clamp(x))
     }
 }
 
@@ -46,6 +39,15 @@ impl From<UnitInterval> for u8 {
 mod tests {
     use super::*;
 
+    #[test]
+    fn clamps() {
+        assert_eq!(UnitInterval::clamp(-1.0), UnitInterval(0.0));
+        assert_eq!(UnitInterval::clamp(0.0), UnitInterval(0.0));
+        assert_eq!(UnitInterval::clamp(0.5), UnitInterval(0.5));
+        assert_eq!(UnitInterval::clamp(1.0), UnitInterval(1.0));
+        assert_eq!(UnitInterval::clamp(2.0), UnitInterval(1.0));
+    }
+
     #[test]
     fn parses_number() {
         assert_eq!(UnitInterval::parse_str("0", ()), Ok(UnitInterval(0.0)));


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]