use crate::formula::value::Value;
use std::collections::HashMap;
use std::rc::Rc;
pub type CustomFn = dyn Fn(&[Value]) -> Value;
#[derive(Clone, Default)]
pub struct CustomFunctions {
by_name: HashMap<String, Rc<CustomFn>>,
}
impl CustomFunctions {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn register(&mut self, name: &str, function: impl Fn(&[Value]) -> Value + 'static) {
self.by_name
.insert(name.to_ascii_uppercase(), Rc::new(function));
}
pub fn remove(&mut self, name: &str) -> bool {
self.by_name.remove(&name.to_ascii_uppercase()).is_some()
}
#[must_use]
pub fn get(&self, name: &str) -> Option<Rc<CustomFn>> {
self.by_name.get(&name.to_ascii_uppercase()).cloned()
}
#[must_use]
pub fn len(&self) -> usize {
self.by_name.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.by_name.is_empty()
}
pub fn names(&self) -> impl Iterator<Item = &str> {
self.by_name.keys().map(String::as_str)
}
}
impl std::fmt::Debug for CustomFunctions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CustomFunctions")
.field("names", &self.by_name.keys().collect::<Vec<_>>())
.finish()
}
}