use super::{bits::abs_bits, common::ONE_SIXTH};
pub(crate) const UCRT_SINF_LIMIT: u32 = 0x4b80_0456;
pub(crate) const UCRT_COSF_LIMIT: u32 = 0x4f49_0fdb;
const SIN_C1: f64 = f64::from_bits(0x3ec71de3a556c734); const SIN_C2: f64 = f64::from_bits(0xbf2a01a01a01a01a); const SIN_C3: f64 = f64::from_bits(0x3f81111111111111); const SIN_C4: f64 = f64::from_bits(0xbfc5555555555555);
const COS_C1: f64 = f64::from_bits(0xbe927e4fb7789f5c); const COS_C2: f64 = f64::from_bits(0x3efa01a01a01a019); const COS_C3: f64 = f64::from_bits(0xbf56c16c16c16c16); const COS_C4: f64 = f64::from_bits(0x3fa5555555555555);
const INV_PIO2: f64 = f64::from_bits(0x3fe45f306dc9c883); const PIO2_HI: f64 = f64::from_bits(0x3ff921fb54400000); const PIO2_LO: f64 = f64::from_bits(0x3dd0b4611a626331);
#[inline]
fn sin_poly(r: f64) -> f64 {
let r2 = r * r;
let p = r2.mul_add(SIN_C1, SIN_C2);
let p = p.mul_add(r2, SIN_C3);
let p = p.mul_add(r2, SIN_C4);
p.mul_add(r * r2, r)
}
#[inline]
fn cos_poly(r: f64) -> f64 {
let r2 = r * r;
let base = 1.0 - r2 * 0.5;
let p = r2.mul_add(COS_C1, COS_C2);
let p = p.mul_add(r2, COS_C3);
let p = p.mul_add(r2, COS_C4);
p.mul_add(r2 * r2, base)
}
#[inline]
fn reduce(a: f64, quadrant: &mut i32) -> f64 {
let n = a.mul_add(INV_PIO2, 0.5) as i32;
let nd = f64::from(n);
let r1 = (-nd).mul_add(PIO2_HI, a);
*quadrant = n & 3;
r1 - nd * PIO2_LO
}
#[inline]
#[must_use]
pub(crate) fn ucrt_sinf(x: f32) -> f32 {
let ax = abs_bits(x);
if ax < 0x3900_0000 {
return x;
}
let d = f64::from(x);
if ax <= 0x3f49_0fdb {
if ax < 0x3c00_0000 {
return (-((d * d) * d)).mul_add(ONE_SIXTH, d) as f32;
}
return sin_poly(d) as f32;
}
let mut q = 0;
let r = reduce(d.abs(), &mut q);
let y = if q & 1 != 0 { cos_poly(r) } else { sin_poly(r) };
if (q >= 2) != (x < 0.0) {
(-y) as f32
} else {
y as f32
}
}
#[inline]
#[must_use]
pub(crate) fn ucrt_cosf(x: f32) -> f32 {
let ax = abs_bits(x);
if ax < 0x3900_0000 {
return 1.0;
}
let d = f64::from(x);
if ax <= 0x3f49_0fdb {
if ax < 0x3c00_0000 {
return (-(d * 0.5)).mul_add(d, 1.0) as f32;
}
return cos_poly(d) as f32;
}
let mut q = 0;
let r = reduce(d.abs(), &mut q);
let y = if q & 1 != 0 { sin_poly(r) } else { cos_poly(r) };
if q == 1 || q == 2 {
(-y) as f32
} else {
y as f32
}
}
#[inline]
#[must_use]
pub(crate) fn sinf(x: f32) -> f32 {
if abs_bits(x) < UCRT_SINF_LIMIT {
ucrt_sinf(x)
} else {
x.sin()
}
}
#[inline]
#[must_use]
pub(crate) fn cosf(x: f32) -> f32 {
if abs_bits(x) < UCRT_COSF_LIMIT {
ucrt_cosf(x)
} else {
x.cos()
}
}