style/values/computed/
angle.rs1use crate::derives::*;
8use crate::typed_om::{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 std::{f32, f64};
16use style_traits::{CssString, CssWriter, ToCss};
17use thin_vec::ThinVec;
18
19#[derive(
21 Add,
22 Animate,
23 Clone,
24 Copy,
25 Debug,
26 Deserialize,
27 MallocSizeOf,
28 PartialEq,
29 PartialOrd,
30 Serialize,
31 ToAnimatedZero,
32 ToResolvedValue,
33)]
34#[repr(C)]
35pub struct Angle(CSSFloat);
36
37impl ToCss for Angle {
38 fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
39 where
40 W: Write,
41 {
42 self.degrees().to_css(dest)?;
43 dest.write_str("deg")
44 }
45}
46
47impl ToTyped for Angle {
48 fn to_typed(&self, dest: &mut ThinVec<TypedValue>) -> Result<(), ()> {
49 dest.push(TypedValue::Numeric(NumericValue::Unit(UnitValue {
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}