style/values/computed/
angle.rs1use crate::derives::*;
8use crate::typed_om::{NumericType, NumericValue, ToTyped, TypedValue, UnitValue};
9use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
10use crate::values::CSSFloat;
11use crate::Zero;
12use std::f64::consts::PI;
13use std::fmt::{self, Write};
14use std::ops::{AddAssign, Neg};
15use style_traits::{CssString, CssWriter, ToCss};
16use thin_vec::ThinVec;
17
18#[derive(
20 Add,
21 Animate,
22 Clone,
23 Copy,
24 Debug,
25 Deserialize,
26 MallocSizeOf,
27 PartialEq,
28 PartialOrd,
29 Serialize,
30 ToAnimatedZero,
31 ToResolvedValue,
32)]
33#[repr(C)]
34pub struct Angle(CSSFloat);
35
36impl ToCss for Angle {
37 fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
38 where
39 W: Write,
40 {
41 self.degrees().to_css(dest)?;
42 dest.write_str("deg")
43 }
44}
45
46impl ToTyped for Angle {
47 fn to_typed(&self, dest: &mut ThinVec<TypedValue>) -> Result<(), ()> {
48 dest.push(TypedValue::Numeric(NumericValue::Unit(UnitValue {
49 numeric_type: NumericType::angle(),
50 value: self.degrees(),
51 unit: CssString::from("deg"),
52 })));
53 Ok(())
54 }
55}
56
57const RAD_PER_DEG: f64 = PI / 180.0;
58
59impl Angle {
60 pub fn from_radians(radians: CSSFloat) -> Self {
62 Angle(radians / RAD_PER_DEG as f32)
63 }
64
65 #[inline]
67 pub fn from_degrees(degrees: CSSFloat) -> Self {
68 Angle(degrees)
69 }
70
71 #[inline]
73 pub fn radians(&self) -> CSSFloat {
74 self.radians64().min(f32::MAX as f64).max(f32::MIN as f64) as f32
75 }
76
77 #[inline]
84 pub fn radians64(&self) -> f64 {
85 self.0 as f64 * RAD_PER_DEG
86 }
87
88 #[inline]
90 pub fn degrees(&self) -> CSSFloat {
91 self.0
92 }
93}
94
95impl Zero for Angle {
96 #[inline]
97 fn zero() -> Self {
98 Angle(0.0)
99 }
100
101 #[inline]
102 fn is_zero(&self) -> bool {
103 self.0 == 0.
104 }
105}
106
107impl ComputeSquaredDistance for Angle {
108 #[inline]
109 fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> {
110 self.radians64()
113 .compute_squared_distance(&other.radians64())
114 }
115}
116
117impl Neg for Angle {
118 type Output = Angle;
119
120 #[inline]
121 fn neg(self) -> Angle {
122 Angle(-self.0)
123 }
124}
125
126impl AddAssign for Angle {
127 fn add_assign(&mut self, rhs: Self) {
128 self.0 += rhs.0
129 }
130}