style/values/computed/
percentage.rs1use crate::derives::*;
8use crate::values::generics::{ClampToNonNegative, NonNegative};
9use crate::values::specified::percentage::ToPercentage;
10use crate::values::{reify_percentage, serialize_normalized_percentage, CSSFloat};
11use crate::Zero;
12use std::fmt;
13use style_traits::{CssWriter, ToCss, ToTyped, TypedValue};
14use thin_vec::ThinVec;
15
16#[derive(
18 Animate,
19 Clone,
20 ComputeSquaredDistance,
21 Copy,
22 Debug,
23 Default,
24 Deserialize,
25 MallocSizeOf,
26 PartialEq,
27 PartialOrd,
28 Serialize,
29 SpecifiedValueInfo,
30 ToAnimatedValue,
31 ToAnimatedZero,
32 ToComputedValue,
33 ToResolvedValue,
34 ToShmem,
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 #[inline]
49 pub fn hundred() -> Self {
50 Percentage(1.)
51 }
52
53 #[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
115impl ToTyped for Percentage {
116 fn to_typed(&self, dest: &mut ThinVec<TypedValue>) -> Result<(), ()> {
117 reify_percentage(self.0, false, dest)
118 }
119}
120
121pub type NonNegativePercentage = NonNegative<Percentage>;
123
124impl NonNegativePercentage {
125 #[inline]
127 pub fn hundred() -> Self {
128 NonNegative(Percentage::hundred())
129 }
130}