use std::sync::OnceLock;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Ufunc {
Arcsinh,
Sinh,
Log,
Log2,
Log10,
Exp,
Exp2,
PowerOf(f64),
}
pub type Evaluator = fn(Ufunc, &mut [f64]) -> bool;
static NUMPY: OnceLock<Evaluator> = OnceLock::new();
pub fn evaluate_with(numpy: Evaluator) {
NUMPY.get_or_init(|| numpy);
}
impl Ufunc {
pub fn map(self, values: &[f64], c_library: impl Fn(f64) -> f64) -> Vec<f64> {
let mut results = values.to_vec();
let evaluated =
!values.is_empty() && NUMPY.get().is_some_and(|numpy| numpy(self, &mut results));
if !evaluated {
for (result, &value) in results.iter_mut().zip(values) {
*result = c_library(value);
}
}
results
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_c_library_computes_without_numpy() {
assert_eq!(
Ufunc::Sinh.map(&[0.0, 1.0], f64::sinh),
[0.0, 1.0_f64.sinh()]
);
assert_eq!(Ufunc::PowerOf(2.0).map(&[3.0], |x| 2f64.powf(x)), [8.0]);
assert_eq!(Ufunc::Log.map(&[], f64::ln), Vec::<f64>::new());
let nan = Ufunc::Arcsinh.map(&[f64::NAN], f64::asinh);
assert!(nan[0].is_nan());
}
}