reval/ruleset/
rule.rs

1use crate::{expr::Expr, value::Value};
2use std::collections::BTreeMap;
3
4/// A rule is an expression with a name
5#[derive(Debug, Clone, PartialEq)]
6pub struct Rule {
7    pub(super) name: String,
8    metadata: BTreeMap<String, Value>,
9    expr: Expr,
10}
11
12impl Rule {
13    /// Construct a new rule from a name and an expression
14    pub fn new(name: impl Into<String>, metadata: BTreeMap<String, Value>, expr: Expr) -> Self {
15        Self {
16            name: name.into(),
17            metadata,
18            expr,
19        }
20    }
21
22    /// Return the name of the rule
23    pub fn name(&self) -> &str {
24        &self.name
25    }
26
27    /// Read a metadata field by name
28    pub fn get_metadata(&self, field: &str) -> Option<&Value> {
29        self.metadata.get(field)
30    }
31
32    pub fn iter_metadata(&self) -> impl Iterator<Item = (&str, &Value)> {
33        self.metadata
34            .iter()
35            .map(|(key, value)| (key.as_ref(), value))
36    }
37
38    /// Return an optional description of the rule
39    pub fn description(&self) -> Option<&str> {
40        match self.metadata.get("description") {
41            Some(Value::String(description)) => Some(description.as_str()),
42            _ => None,
43        }
44    }
45
46    pub fn expr(&self) -> &Expr {
47        &self.expr
48    }
49}