nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
//! Platform decimal operations for standard-mode roots and scientific notation.
//! Other targets retain the mathematical root; Foundation overflow quirks are macOS-only.
pub(crate) fn root(value: f64, degree: f64) -> Option<f64> {
    if value < 0.0 && degree % 2.0 == 1.0 {
        return Some(-(-value).powf(1.0 / degree));
    }
    #[cfg(target_os = "macos")]
    if value != 0.0 && degree > 1.0 && degree <= 1024.0 {
        return platform::root(value, degree);
    }
    let result = value.powf(1.0 / degree);
    result.is_finite().then_some(result)
}
/// Scientific notation uses platform decimal powers and reciprocals.
/// Foundation reserves precision in division, so its lower exponent boundary
/// differs from direct decimal string initialization. Preserve its NaN sentinel.
pub(crate) fn scientific_scale_invalid(exponent: i32) -> bool {
    #[cfg(target_os = "macos")]
    {
        platform::scientific_scale_invalid(exponent)
    }
    #[cfg(not(target_os = "macos"))]
    {
        !(-90..=127).contains(&exponent)
    }
}
#[cfg(target_os = "macos")]
mod platform {
    // NSDecimal's public C layout: exponent:8, length:4, negative:1, compact:1,
    // reserved:18, followed by eight little-endian 16-bit mantissa words.
    #[repr(C)]
    #[derive(Clone, Copy, Default)]
    struct Decimal {
        flags: u32,
        mantissa: [u16; 8],
    }
    #[link(name = "Foundation", kind = "framework")]
    unsafe extern "C" {
        fn NSDecimalPower(
            out: *mut Decimal,
            value: *const Decimal,
            power: usize,
            rounding: usize,
        ) -> usize;
        fn NSDecimalDivide(
            out: *mut Decimal,
            a: *const Decimal,
            b: *const Decimal,
            rounding: usize,
        ) -> usize;
        fn NSDecimalMultiply(
            out: *mut Decimal,
            a: *const Decimal,
            b: *const Decimal,
            rounding: usize,
        ) -> usize;
        fn NSDecimalAdd(
            out: *mut Decimal,
            a: *const Decimal,
            b: *const Decimal,
            rounding: usize,
        ) -> usize;
    }
    impl Decimal {
        fn new(value: f64) -> Option<Self> {
            let text = format!("{:e}", value.abs());
            let (digits, exponent) = text.split_once('e').map_or((text.as_str(), 0), |(n, e)| {
                (n, e.parse::<i32>().unwrap_or(0))
            });
            let exponent = exponent - digits.split_once('.').map_or(0, |(_, f)| f.len() as i32);
            let coefficient = digits.replace('.', "").parse::<u128>().ok()?;
            let exponent = i8::try_from(exponent).ok()?;
            let mut mantissa = [0; 8];
            let mut length = 0;
            for (i, word) in mantissa.iter_mut().enumerate() {
                *word = (coefficient >> (i * 16)) as u16;
                if *word != 0 {
                    length = i + 1;
                }
            }
            Some(Self {
                flags: exponent as u8 as u32
                    | ((length as u32) << 8)
                    | (u32::from(value < 0.0) << 12),
                mantissa,
            })
        }
        fn value(self) -> Option<f64> {
            if self.flags & 0x1f00 == 0x1000 {
                return None;
            }
            let coefficient = self
                .mantissa
                .iter()
                .enumerate()
                .fold(0u128, |n, (i, w)| n | ((*w as u128) << (i * 16)));
            let value = coefficient as f64 * 10f64.powi(self.flags as u8 as i8 as i32);
            Some(if self.flags & 0x1000 != 0 {
                -value
            } else {
                value
            })
        }
    }
    pub(super) fn scientific_scale_invalid(exponent: i32) -> bool {
        if exponent.unsigned_abs() > 1024 {
            return true;
        }
        let ten = Decimal {
            flags: 1 << 8,
            mantissa: [10, 0, 0, 0, 0, 0, 0, 0],
        };
        let one = Decimal {
            flags: 1 << 8,
            mantissa: [1, 0, 0, 0, 0, 0, 0, 0],
        };
        let mut power = Decimal::default();
        // C-layout operands live for the call; output does not alias either input.
        unsafe {
            NSDecimalPower(&mut power, &ten, exponent.unsigned_abs() as usize, 0);
        }
        if exponent < 0 {
            let mut reciprocal = Decimal::default();
            unsafe {
                NSDecimalDivide(&mut reciprocal, &one, &power, 0);
            }
            power = reciprocal;
        }
        power.value().is_none()
    }
    pub(super) fn root(value: f64, degree: f64) -> Option<f64> {
        let a = Decimal::new(value)?;
        let n = Decimal::new(degree)?;
        let previous = Decimal::new(degree - 1.0)?;
        let mut x = a;
        // ponytail: bounded Newton iteration; expand only for observed high-degree cases.
        for _ in 0..1000 {
            let (mut power, mut quotient, mut product, mut sum, mut next) = (
                Decimal::default(),
                Decimal::default(),
                Decimal::default(),
                Decimal::default(),
                Decimal::default(),
            );
            // Each pointer addresses a live, correctly aligned C-layout value; outputs do
            // not alias inputs. Foundation writes at most one NSDecimal to each output.
            unsafe {
                if degree.fract() == 0.0 {
                    NSDecimalPower(&mut power, &x, degree as usize - 1, 0);
                } else {
                    let Some(p) = Decimal::new(x.value()?.powf(degree - 1.0)) else {
                        return x.value();
                    };
                    power = p;
                }
                if power.value().is_none() {
                    return x.value();
                }
                NSDecimalDivide(&mut quotient, &a, &power, 0);
                NSDecimalMultiply(&mut product, &previous, &x, 0);
                NSDecimalAdd(&mut sum, &quotient, &product, 0);
                NSDecimalDivide(&mut next, &sum, &n, 0);
            }
            let result = next.value()?;
            if (result - x.value()?).abs() < 1e-10 {
                return Some(result);
            }
            x = next;
        }
        // The word-root operation returns its last bounded iterate,
        // even when an even root of a negative number has no real solution.
        (value < 0.0).then(|| x.value()).flatten()
    }
}

pub(crate) fn exponent(value: f64) -> f64 {
    // Standard exponentiation takes a twelfth-denominator convergent
    // when one occurs before a larger continued-fraction denominator.
    let mut fraction = value.rem_euclid(1.0);
    let (mut p0, mut p1, mut q0, mut q1) = (0.0, 1.0, 1.0, 0.0);
    let mut exponent = value;
    for _ in 0..16 {
        let whole = fraction.floor();
        let (p, q) = (whole * p1 + p0, whole * q1 + q0);
        if q > 12.0 {
            break;
        }
        if q == 12.0 {
            exponent = value.floor() + p / q;
            break;
        }
        (p0, p1, q0, q1) = (p1, p, q1, q);
        let rest = fraction - whole;
        if rest == 0.0 {
            break;
        }
        fraction = 1.0 / rest;
    }
    exponent
}