zen_engine/loader/
closure.rs

1use crate::loader::{DecisionLoader, LoaderResponse};
2use std::fmt::{Debug, Formatter};
3use std::future::Future;
4use std::pin::Pin;
5
6/// Loads decisions using an async closure
7pub struct ClosureLoader<F>
8where
9    F: Sync + Send,
10{
11    closure: F,
12}
13
14impl<T> Debug for ClosureLoader<T>
15where
16    T: Sync + Send,
17{
18    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
19        write!(f, "ClosureLoader")
20    }
21}
22
23impl<F, O> ClosureLoader<F>
24where
25    F: Fn(String) -> O + Sync + Send,
26    O: Future<Output = LoaderResponse> + Send,
27{
28    pub fn new(closure: F) -> Self {
29        Self { closure }
30    }
31}
32
33impl<F, O> DecisionLoader for ClosureLoader<F>
34where
35    F: Fn(String) -> O + Sync + Send,
36    O: Future<Output = LoaderResponse> + Send,
37{
38    fn load<'a>(
39        &'a self,
40        key: &'a str,
41    ) -> Pin<Box<dyn Future<Output = LoaderResponse> + 'a + Send>> {
42        Box::pin(async move {
43            let closure = &self.closure;
44            closure(key.to_string()).await
45        })
46    }
47}