use std::collections::HashMap;
use crate::error::{Error, Result};
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, PartialOrd, Ord, Eq)]
pub enum Gate {
And(Vec<Gate>),
Or(Vec<Gate>),
Not(Vec<Gate>),
Value(String),
}
impl Gate {
pub fn execute(self, data: &HashMap<String, bool>) -> Result<bool> {
match self {
Gate::Value(s) => {
let var_val = data.get(s.as_str());
if var_val.is_none() {
return Err(Error::VariableNotFound(s));
}
Ok(var_val.unwrap().to_owned()) }
Gate::Not(s) => {
let val = s[0].clone().execute(data)?;
Ok(!val)
}
Gate::Or(s) => {
let mut acc = false;
for val in s {
let value = val.execute(data)?;
acc |= value;
}
Ok(acc)
}
Gate::And(s) => {
let mut acc = true;
for gate in s {
let value = gate.execute(data)?;
acc &= value;
}
Ok(acc)
}
}
}
}