mf_expression/functions/
method.rs1use crate::functions::date_method::DateMethod;
6use crate::functions::defs::FunctionDefinition;
7use nohash_hasher::{BuildNoHashHasher, IsEnabled};
8use std::cell::RefCell;
9use std::collections::HashMap;
10use std::fmt::Display;
11use std::rc::Rc;
12use strum::IntoEnumIterator;
13
14impl IsEnabled for DateMethod {}
15
16#[derive(Debug, PartialEq, Eq, Clone)]
20pub enum MethodKind {
21 DateMethod(DateMethod),
23}
24
25impl TryFrom<&str> for MethodKind {
26 type Error = strum::ParseError;
27
28 fn try_from(value: &str) -> Result<Self, Self::Error> {
37 DateMethod::try_from(value).map(MethodKind::DateMethod)
38 }
39}
40
41impl Display for MethodKind {
42 fn fmt(
43 &self,
44 f: &mut std::fmt::Formatter<'_>,
45 ) -> std::fmt::Result {
46 match self {
47 MethodKind::DateMethod(d) => write!(f, "{d}"),
48 }
49 }
50}
51
52pub struct MethodRegistry {
56 date_methods: HashMap<
58 DateMethod,
59 Rc<dyn FunctionDefinition>,
60 BuildNoHashHasher<DateMethod>,
61 >,
62}
63
64impl MethodRegistry {
65 thread_local!(
67 static INSTANCE: RefCell<MethodRegistry> = RefCell::new(MethodRegistry::new_internal())
68 );
69
70 pub fn get_definition(
79 kind: &MethodKind
80 ) -> Option<Rc<dyn FunctionDefinition>> {
81 match kind {
82 MethodKind::DateMethod(dm) => {
83 Self::INSTANCE.with_borrow(|i| i.date_methods.get(&dm).cloned())
84 },
85 }
86 }
87
88 fn new_internal() -> Self {
92 let date_methods =
94 DateMethod::iter().map(|i| (i.clone(), (&i).into())).collect();
95
96 Self { date_methods }
97 }
98}