style/values/computed/
percentage.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! Computed percentages.
6
7use crate::derives::*;
8use crate::values::generics::{ClampToNonNegative, NonNegative};
9use crate::values::specified::percentage::ToPercentage;
10use crate::values::{serialize_normalized_percentage, CSSFloat};
11use crate::Zero;
12use std::fmt;
13use style_traits::{CssWriter, ToCss};
14
15/// A computed percentage.
16#[derive(
17    Animate,
18    Clone,
19    ComputeSquaredDistance,
20    Copy,
21    Debug,
22    Default,
23    Deserialize,
24    MallocSizeOf,
25    PartialEq,
26    PartialOrd,
27    Serialize,
28    SpecifiedValueInfo,
29    ToAnimatedValue,
30    ToAnimatedZero,
31    ToComputedValue,
32    ToResolvedValue,
33    ToShmem,
34    ToTyped,
35)]
36#[repr(C)]
37pub struct Percentage(pub CSSFloat);
38
39impl ClampToNonNegative for Percentage {
40    #[inline]
41    fn clamp_to_non_negative(self) -> Self {
42        Percentage(self.0.max(0.))
43    }
44}
45
46impl Percentage {
47    /// 100%
48    #[inline]
49    pub fn hundred() -> Self {
50        Percentage(1.)
51    }
52
53    /// Returns the absolute value for this percentage.
54    #[inline]
55    pub fn abs(&self) -> Self {
56        Percentage(self.0.abs())
57    }
58}
59
60impl Zero for Percentage {
61    fn zero() -> Self {
62        Percentage(0.)
63    }
64
65    fn is_zero(&self) -> bool {
66        self.0 == 0.
67    }
68}
69
70impl ToPercentage for Percentage {
71    fn to_percentage(&self) -> CSSFloat {
72        self.0
73    }
74}
75
76impl std::ops::AddAssign for Percentage {
77    fn add_assign(&mut self, other: Self) {
78        self.0 += other.0
79    }
80}
81
82impl std::ops::Add for Percentage {
83    type Output = Self;
84
85    fn add(self, other: Self) -> Self {
86        Percentage(self.0 + other.0)
87    }
88}
89
90impl std::ops::Sub for Percentage {
91    type Output = Self;
92
93    fn sub(self, other: Self) -> Self {
94        Percentage(self.0 - other.0)
95    }
96}
97
98impl std::ops::Rem for Percentage {
99    type Output = Self;
100
101    fn rem(self, other: Self) -> Self {
102        Percentage(self.0 % other.0)
103    }
104}
105
106impl ToCss for Percentage {
107    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
108    where
109        W: fmt::Write,
110    {
111        serialize_normalized_percentage(self.0, dest)
112    }
113}
114
115/// A wrapper over a `Percentage`, whose value should be clamped to 0.
116pub type NonNegativePercentage = NonNegative<Percentage>;
117
118impl NonNegativePercentage {
119    /// 100%
120    #[inline]
121    pub fn hundred() -> Self {
122        NonNegative(Percentage::hundred())
123    }
124}