filter_expr_evaler/
ctx.rs1use std::{
2 collections::BTreeMap,
3 fmt::{self, Debug},
4};
5
6use crate::Value;
7
8use crate::Error;
9
10#[async_trait::async_trait]
12pub trait Context: Send + Sync {
13 async fn get_var(&self, name: &str) -> Result<Option<Value>, Error>;
22}
23
24#[macro_export]
37macro_rules! simple_context {
38 () => {
40 $crate::SimpleContext::new(std::collections::BTreeMap::new())
41 };
42
43 ($key:literal : $value:expr $(,)?) => {
45 $crate::SimpleContext::new(std::collections::BTreeMap::from([
46 ($key.to_string(), ($value).into()),
47 ]))
48 };
49
50 ($key:literal : $value:expr, $($rest_key:literal : $rest_value:expr),* $(,)?) => {
52 $crate::SimpleContext::new(std::collections::BTreeMap::from([
53 ($key.to_string(), ($value).into()),
54 $(($rest_key.to_string(), ($rest_value).into())),*
55 ]))
56 };
57}
58
59pub struct SimpleContext {
64 vars: BTreeMap<String, Value>,
65}
66
67impl Debug for SimpleContext {
68 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69 write!(f, "SimpleContext {{ vars: {:?} }}", self.vars)?;
70 Ok(())
71 }
72}
73
74impl SimpleContext {
75 pub fn new(vars: BTreeMap<String, Value>) -> Self {
76 Self { vars }
77 }
78}
79
80#[async_trait::async_trait]
81impl Context for SimpleContext {
82 async fn get_var(&self, name: &str) -> Result<Option<Value>, Error> {
83 Ok(self.vars.get(name).cloned())
84 }
85}