frequenz_microgrid_formula_engine/
formula_engine.rs

1// License: MIT
2// Copyright © 2024 Frequenz Energy-as-a-Service GmbH
3
4use crate::traits::NumberLike;
5use std::collections::{HashMap, HashSet};
6use std::fmt::Debug;
7use std::str::FromStr;
8
9use crate::{error::FormulaError, expression::Expr, parser};
10
11/// FormulaEngine holds the parsed expression and can calculate the result
12/// based on the provided component values.
13#[derive(Debug)]
14pub struct FormulaEngine<T> {
15    expr: Expr<T>,
16    components: HashSet<u64>,
17}
18
19impl<T: FromStr + NumberLike<T> + PartialOrd> FormulaEngine<T>
20where
21    <T as FromStr>::Err: Debug,
22{
23    /// Create a new FormulaEngine from a formula string.
24    pub fn try_new(s: &str) -> Result<Self, FormulaError> {
25        let expr = parser::parse(s)?;
26
27        let components = expr.components();
28
29        Ok(Self { expr, components })
30    }
31
32    /// Get the components of the formula.
33    pub fn components(&self) -> &HashSet<u64> {
34        &self.components
35    }
36
37    /// Calculate the result of the formula based on the provided component values.
38    pub fn calculate(&self, values: &HashMap<u64, Option<T>>) -> Result<Option<T>, FormulaError> {
39        self.expr.calculate(values)
40    }
41}