Skip to main content

ergo_runtime/source/implementations/context_bool/
impl.rs

1use std::collections::HashMap;
2
3use crate::common::Value;
4use crate::runtime::ExecutionContext;
5use crate::source::{ParameterValue, SourcePrimitive, SourcePrimitiveManifest};
6
7use super::manifest::context_bool_source_manifest;
8
9const DEFAULT_CONTEXT_KEY: &str = "x";
10const KEY_PARAMETER: &str = "key";
11
12pub struct ContextBoolSource {
13    manifest: SourcePrimitiveManifest,
14}
15
16impl ContextBoolSource {
17    pub fn new() -> Self {
18        Self {
19            manifest: context_bool_source_manifest(),
20        }
21    }
22}
23
24impl Default for ContextBoolSource {
25    fn default() -> Self {
26        Self::new()
27    }
28}
29
30impl SourcePrimitive for ContextBoolSource {
31    fn manifest(&self) -> &SourcePrimitiveManifest {
32        &self.manifest
33    }
34
35    fn produce(
36        &self,
37        parameters: &HashMap<String, ParameterValue>,
38        ctx: &ExecutionContext,
39    ) -> HashMap<String, Value> {
40        let context_key = parameters
41            .get(KEY_PARAMETER)
42            .and_then(|v| match v {
43                ParameterValue::String(s) => Some(s.as_str()),
44                _ => None,
45            })
46            .unwrap_or(DEFAULT_CONTEXT_KEY);
47
48        let value = ctx
49            .value(context_key)
50            .and_then(|v| v.as_bool())
51            .unwrap_or(false);
52
53        HashMap::from([("value".to_string(), Value::Bool(value))])
54    }
55}