use crate::derives::*;
use crate::typed_om::{NumericValue, ToTyped, TypedValue, UnitValue};
use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
use crate::values::CSSFloat;
use crate::Zero;
use std::f64::consts::PI;
use std::fmt::{self, Write};
use std::ops::{AddAssign, Neg};
use std::{f32, f64};
use style_traits::{CssString, CssWriter, ToCss};
use thin_vec::ThinVec;
#[derive(
Add,
Animate,
Clone,
Copy,
Debug,
Deserialize,
MallocSizeOf,
PartialEq,
PartialOrd,
Serialize,
ToAnimatedZero,
ToResolvedValue,
)]
#[repr(C)]
pub struct Angle(CSSFloat);
impl ToCss for Angle {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
self.degrees().to_css(dest)?;
dest.write_str("deg")
}
}
impl ToTyped for Angle {
fn to_typed(&self, dest: &mut ThinVec<TypedValue>) -> Result<(), ()> {
dest.push(TypedValue::Numeric(NumericValue::Unit(UnitValue {
value: self.degrees(),
unit: CssString::from("deg"),
})));
Ok(())
}
}
const RAD_PER_DEG: f64 = PI / 180.0;
impl Angle {
pub fn from_radians(radians: CSSFloat) -> Self {
Angle(radians / RAD_PER_DEG as f32)
}
#[inline]
pub fn from_degrees(degrees: CSSFloat) -> Self {
Angle(degrees)
}
#[inline]
pub fn radians(&self) -> CSSFloat {
self.radians64().min(f32::MAX as f64).max(f32::MIN as f64) as f32
}
#[inline]
pub fn radians64(&self) -> f64 {
self.0 as f64 * RAD_PER_DEG
}
#[inline]
pub fn degrees(&self) -> CSSFloat {
self.0
}
}
impl Zero for Angle {
#[inline]
fn zero() -> Self {
Angle(0.0)
}
#[inline]
fn is_zero(&self) -> bool {
self.0 == 0.
}
}
impl ComputeSquaredDistance for Angle {
#[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> {
self.radians64()
.compute_squared_distance(&other.radians64())
}
}
impl Neg for Angle {
type Output = Angle;
#[inline]
fn neg(self) -> Angle {
Angle(-self.0)
}
}
impl AddAssign for Angle {
fn add_assign(&mut self, rhs: Self) {
self.0 += rhs.0
}
}