summaryrefslogtreecommitdiff
path: root/src/geom/relative.rs
blob: c2d0a0cb0327a9645a36543fb6481031da8fa290 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
use super::*;

/// A relative length.
///
/// _Note_: `50%` is represented as `0.5` here, but stored as `50.0` in the
/// corresponding [literal](crate::syntax::Lit::Percent).
#[derive(Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Relative(N64);

impl Relative {
    /// A ratio of `0%` represented as `0.0`.
    pub fn zero() -> Self {
        Self(N64::from(0.0))
    }

    /// A ratio of `100%` represented as `1.0`.
    pub fn one() -> Self {
        Self(N64::from(1.0))
    }

    /// Create a new relative value.
    pub fn new(ratio: f64) -> Self {
        Self(N64::from(ratio))
    }

    /// Get the underlying ratio.
    pub fn get(self) -> f64 {
        self.0.into()
    }

    /// Resolve this relative to the given `length`.
    pub fn resolve(self, length: Length) -> Length {
        // We don't want NaNs.
        if length.is_infinite() {
            Length::zero()
        } else {
            self.get() * length
        }
    }

    /// Whether the ratio is zero.
    pub fn is_zero(self) -> bool {
        self.0 == 0.0
    }

    /// The absolute value of the this relative.
    pub fn abs(self) -> Self {
        Self::new(self.get().abs())
    }
}

impl Debug for Relative {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "{}%", 100.0 * self.get())
    }
}

impl Neg for Relative {
    type Output = Self;

    fn neg(self) -> Self {
        Self(-self.0)
    }
}

impl Add for Relative {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self(self.0 + other.0)
    }
}

sub_impl!(Relative - Relative -> Relative);

impl Mul<f64> for Relative {
    type Output = Self;

    fn mul(self, other: f64) -> Self {
        Self(self.0 * other)
    }
}

impl Mul<Relative> for f64 {
    type Output = Relative;

    fn mul(self, other: Relative) -> Relative {
        other * self
    }
}

impl Div<f64> for Relative {
    type Output = Self;

    fn div(self, other: f64) -> Self {
        Self(self.0 / other)
    }
}

impl Div for Relative {
    type Output = f64;

    fn div(self, other: Self) -> f64 {
        self.get() / other.get()
    }
}

assign_impl!(Relative += Relative);
assign_impl!(Relative -= Relative);
assign_impl!(Relative *= f64);
assign_impl!(Relative /= f64);