[librsvg: 1/3] Implement Parse for NumberOrPercentage




commit 13d640910fa043969eebc6512d500030873cf882
Author: John Ledbetter <john ledbetter gmail com>
Date:   Fri May 7 09:41:02 2021 -0400

    Implement Parse for NumberOrPercentage
    
    See https://www.w3.org/TR/css3-values/#typedef-number-percentage
    
    Many of the filter functions take a NumberOrPercentage as an argument,
    so it makes sense that this functionality should be implemented once
    somewhere and re-used between the various filters.

 src/parsers.rs | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)
---
diff --git a/src/parsers.rs b/src/parsers.rs
index c1bb1b3a..528d0de7 100644
--- a/src/parsers.rs
+++ b/src/parsers.rs
@@ -110,6 +110,31 @@ impl<T: Parse + Copy> Parse for NumberOptionalNumber<T> {
     }
 }
 
+/// CSS number-percentage
+///
+/// https://www.w3.org/TR/css3-values/#typedef-number-percentage
+#[derive(Debug, Copy, Clone, PartialEq)]
+pub struct NumberOrPercentage {
+    pub value: f64,
+}
+
+impl Parse for NumberOrPercentage {
+    fn parse<'i>(parser: &mut Parser<'i, '_>) -> Result<Self, ParseError<'i>> {
+        let loc = parser.current_source_location();
+
+        let value = match parser.next()? {
+            Token::Number { value, .. } => Ok(*value),
+            Token::Percentage { unit_value, .. } => Ok(*unit_value),
+            tok => Err(loc.new_unexpected_token_error(tok.clone())),
+        }?;
+
+        let v = finite_f32(value).map_err(|e| parser.new_custom_error(e))?;
+        Ok(NumberOrPercentage {
+            value: f64::from(v),
+        })
+    }
+}
+
 impl Parse for i32 {
     /// CSS integer
     ///


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