use std::str::FromStr;
use pest::iterators::Pair;
use crate::{
config::Limit,
error::{CompileError, ParseEnumError},
parser::Rule,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Compare {
Gte,
Gt,
Lte,
Lt,
Eq,
}
impl FromStr for Compare {
type Err = ParseEnumError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let cmp = match s {
">=" => Self::Gte,
">" => Self::Gt,
"<=" => Self::Lte,
"<" => Self::Lt,
"=" => Self::Eq,
_ => return Err(ParseEnumError),
};
Ok(cmp)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Checker {
pub compare: Compare,
pub target: i64,
}
impl Checker {
pub(crate) fn from_pair(pair: Pair<'_, Rule>, limit: &Limit<'_>) -> Result<Self, CompileError> {
assert_eq!(pair.as_rule(), Rule::checker);
let mut pairs = pair.into_inner();
let compare = pairs.next().unwrap().as_str().parse().unwrap();
let target = pairs.next().unwrap().as_str().parse::<i64>()?;
limit.check_number_item(target)?;
Ok(Self { compare, target })
}
#[must_use]
pub fn check(&self, result: i64) -> bool {
match result.cmp(&self.target) {
std::cmp::Ordering::Greater => {
std::matches!(self.compare, Compare::Gte | Compare::Gt)
}
std::cmp::Ordering::Less => {
std::matches!(self.compare, Compare::Lte | Compare::Lt)
}
std::cmp::Ordering::Equal => {
std::matches!(self.compare, Compare::Gte | Compare::Lte | Compare::Eq)
}
}
}
}