lewp_css/domain/expressions/
calculable_property_value.rs

1// This file is part of css. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/css/master/COPYRIGHT. No part of predicator, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
2// Copyright © 2017 The developers of css. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/css/master/COPYRIGHT.
3
4use {
5    super::{AttrFunction, CalcFunction, Expression, VarFunction},
6    crate::domain::units::{conversions::*, PercentageUnit, Unit},
7    cssparser::ToCss,
8    std::fmt,
9    CalculablePropertyValue::*,
10};
11
12#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
13pub enum CalculablePropertyValue<U: Unit> {
14    Constant(U),
15
16    Percentage(PercentageUnit<U::Number>),
17
18    Calc(CalcFunction<U>),
19
20    Attr(AttrFunction),
21
22    Var(VarFunction),
23}
24
25impl<U: Unit> Default for CalculablePropertyValue<U> {
26    #[inline(always)]
27    fn default() -> Self {
28        CalculablePropertyValue::Constant(U::default())
29    }
30}
31
32impl<U: Unit> ToCss for CalculablePropertyValue<U> {
33    fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
34        match *self {
35            Constant(ref constant) => constant.to_css(dest),
36
37            Percentage(ref percentage) => percentage.to_css(dest),
38
39            Calc(ref function) => function.to_css(dest),
40
41            Attr(ref function) => function.to_css(dest),
42
43            Var(ref function) => function.to_css(dest),
44        }
45    }
46}
47
48impl<U: Unit> Expression<U> for CalculablePropertyValue<U> {
49    /// Evaluate the CalculablePropertyValue by returning the numeric value of the canonical dimension
50    /// Division by zero is handled by returning the maximum possible f32 value
51    /// Subtractions for UnsignedCssNumber that are negative are handled by returning 0.0
52    #[inline(always)]
53    fn evaluate<
54        Conversion: FontRelativeLengthConversion<U::Number>
55            + ViewportPercentageLengthConversion<U::Number>
56            + PercentageConversion<U::Number>
57            + AttributeConversion<U>
58            + CssVariableConversion,
59    >(
60        &self,
61        conversion: &Conversion,
62    ) -> Option<U::Number> {
63        match *self {
64            Constant(ref constant) => Some(constant.to_CssNumber()),
65
66            Percentage(ref percentage) => {
67                Some(percentage.to_absolute_value(conversion))
68            }
69
70            Calc(ref function) => function.evaluate(conversion),
71
72            Attr(ref function) => function.evaluate(conversion),
73
74            Var(ref function) => function.evaluate(conversion),
75        }
76    }
77}