#![forbid(unsafe_code)]
#![warn(missing_docs)]
use std::error::Error as StdError;
use std::fmt;
use std::sync::Arc;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Status {
Accepted,
Rejected,
}
impl Status {
pub const fn is_accepted(self) -> bool {
matches!(self, Self::Accepted)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Decision {
policy: String,
status: Status,
explanation: String,
children: Vec<Decision>,
}
impl Decision {
pub fn leaf(policy: impl Into<String>, status: Status, explanation: impl Into<String>) -> Self {
Self {
policy: policy.into(),
status,
explanation: explanation.into(),
children: Vec::new(),
}
}
fn composite(
policy: String,
status: Status,
explanation: impl Into<String>,
children: Vec<Self>,
) -> Self {
Self {
policy,
status,
explanation: explanation.into(),
children,
}
}
pub fn policy(&self) -> &str {
&self.policy
}
pub const fn status(&self) -> Status {
self.status
}
pub const fn is_accepted(&self) -> bool {
self.status.is_accepted()
}
pub fn explanation(&self) -> &str {
&self.explanation
}
pub fn children(&self) -> &[Self] {
&self.children
}
pub fn walk(&self) -> impl Iterator<Item = &Self> {
DecisionWalk { stack: vec![self] }
}
}
struct DecisionWalk<'a> {
stack: Vec<&'a Decision>,
}
impl<'a> Iterator for DecisionWalk<'a> {
type Item = &'a Decision;
fn next(&mut self) -> Option<Self::Item> {
let current = self.stack.pop()?;
self.stack.extend(current.children.iter().rev());
Some(current)
}
}
type Evaluator<T> = dyn Fn(&T) -> Decision + Send + Sync + 'static;
pub struct Policy<T> {
name: String,
evaluator: Arc<Evaluator<T>>,
}
impl<T> Clone for Policy<T> {
fn clone(&self) -> Self {
Self {
name: self.name.clone(),
evaluator: Arc::clone(&self.evaluator),
}
}
}
impl<T> fmt::Debug for Policy<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Policy").field("name", &self.name).finish()
}
}
impl<T: 'static> Policy<T> {
pub fn allow_if(
name: impl Into<String>,
expectation: impl Into<String>,
predicate: impl Fn(&T) -> bool + Send + Sync + 'static,
) -> Result<Self, Error> {
let name = valid_name(name.into())?;
let expectation = expectation.into();
let decision_name = name.clone();
let evaluator = move |value: &T| {
let status = if predicate(value) {
Status::Accepted
} else {
Status::Rejected
};
Decision::leaf(decision_name.clone(), status, expectation.clone())
};
Ok(Self {
name,
evaluator: Arc::new(evaluator),
})
}
pub fn explain_with(
name: impl Into<String>,
evaluator: impl Fn(&T) -> (bool, String) + Send + Sync + 'static,
) -> Result<Self, Error> {
let name = valid_name(name.into())?;
let decision_name = name.clone();
Ok(Self {
name,
evaluator: Arc::new(move |value| {
let (accepted, explanation) = evaluator(value);
let status = if accepted {
Status::Accepted
} else {
Status::Rejected
};
Decision::leaf(decision_name.clone(), status, explanation)
}),
})
}
pub fn all(
name: impl Into<String>,
policies: impl IntoIterator<Item = Self>,
) -> Result<Self, Error> {
Self::combine(name.into(), policies, Composite::All)
}
pub fn any(
name: impl Into<String>,
policies: impl IntoIterator<Item = Self>,
) -> Result<Self, Error> {
Self::combine(name.into(), policies, Composite::Any)
}
fn combine(
name: String,
policies: impl IntoIterator<Item = Self>,
mode: Composite,
) -> Result<Self, Error> {
let name = valid_name(name)?;
let policies: Vec<Self> = policies.into_iter().collect();
if policies.is_empty() {
return Err(Error::EmptyComposite);
}
let decision_name = name.clone();
Ok(Self {
name,
evaluator: Arc::new(move |value| {
let children: Vec<_> = policies.iter().map(|rule| rule.evaluate(value)).collect();
let accepted = match mode {
Composite::All => children.iter().all(Decision::is_accepted),
Composite::Any => children.iter().any(Decision::is_accepted),
};
let (status, explanation) = match (mode, accepted) {
(Composite::All, true) => (Status::Accepted, "all child policies accepted"),
(Composite::All, false) => {
(Status::Rejected, "one or more child policies rejected")
}
(Composite::Any, true) => {
(Status::Accepted, "one or more child policies accepted")
}
(Composite::Any, false) => (Status::Rejected, "all child policies rejected"),
};
Decision::composite(decision_name.clone(), status, explanation, children)
}),
})
}
pub fn not(self, name: impl Into<String>) -> Result<Self, Error> {
let name = valid_name(name.into())?;
let decision_name = name.clone();
Ok(Self {
name,
evaluator: Arc::new(move |value| {
let child = self.evaluate(value);
let status = if child.is_accepted() {
Status::Rejected
} else {
Status::Accepted
};
Decision::composite(
decision_name.clone(),
status,
"child policy result was inverted",
vec![child],
)
}),
})
}
pub fn evaluate(&self, value: &T) -> Decision {
(self.evaluator)(value)
}
pub fn name(&self) -> &str {
&self.name
}
}
impl<T> Policy<T>
where
T: PartialOrd + fmt::Display + Send + Sync + Copy + 'static,
{
pub fn inclusive_range(name: impl Into<String>, minimum: T, maximum: T) -> Result<Self, Error> {
if minimum > maximum {
return Err(Error::ReversedRange);
}
Self::explain_with(name, move |value| {
(
*value >= minimum && *value <= maximum,
format!("expected {minimum} <= value <= {maximum}; observed {value}"),
)
})
}
pub fn exclusive_range(name: impl Into<String>, minimum: T, maximum: T) -> Result<Self, Error> {
if minimum >= maximum {
return Err(Error::ReversedRange);
}
Self::explain_with(name, move |value| {
(
*value > minimum && *value < maximum,
format!("expected {minimum} < value < {maximum}; observed {value}"),
)
})
}
}
impl Policy<f64> {
pub fn absolute_tolerance(
name: impl Into<String>,
target: f64,
tolerance: f64,
) -> Result<Self, Error> {
validate_float_rule(target, tolerance)?;
Self::explain_with(name, move |value| {
let distance = (*value - target).abs();
let accepted = value.is_finite() && distance <= tolerance;
(
accepted,
format!(
"absolute distance {distance} must be <= {tolerance} around target {target}"
),
)
})
}
pub fn relative_tolerance(
name: impl Into<String>,
target: f64,
fraction: f64,
absolute_floor: f64,
) -> Result<Self, Error> {
validate_float_rule(target, fraction)?;
if !absolute_floor.is_finite() || absolute_floor < 0.0 {
return Err(Error::InvalidTolerance(absolute_floor));
}
let tolerance = (target.abs() * fraction).max(absolute_floor);
if !tolerance.is_finite() {
return Err(Error::InvalidTolerance(tolerance));
}
Self::explain_with(name, move |value| {
let distance = (*value - target).abs();
(
value.is_finite() && distance <= tolerance,
format!(
"relative distance {distance} must be <= {tolerance} around target {target}"
),
)
})
}
}
#[derive(Debug, Clone, Copy)]
enum Composite {
All,
Any,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Error {
EmptyName,
EmptyComposite,
ReversedRange,
InvalidTolerance(f64),
NonFiniteTarget(f64),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::EmptyName => f.write_str("policy name cannot be empty"),
Self::EmptyComposite => f.write_str("composite policy needs at least one child"),
Self::ReversedRange => f.write_str("range boundaries are reversed or empty"),
Self::InvalidTolerance(value) => write!(f, "invalid tolerance: {value}"),
Self::NonFiniteTarget(value) => write!(f, "target must be finite: {value}"),
}
}
}
impl StdError for Error {}
fn valid_name(name: String) -> Result<String, Error> {
if name.trim().is_empty() {
Err(Error::EmptyName)
} else {
Ok(name)
}
}
fn validate_float_rule(target: f64, tolerance: f64) -> Result<(), Error> {
if !target.is_finite() {
return Err(Error::NonFiniteTarget(target));
}
if !tolerance.is_finite() || tolerance < 0.0 {
return Err(Error::InvalidTolerance(tolerance));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn absolute_tolerance_includes_boundary_and_rejects_nan() {
let policy = Policy::absolute_tolerance("sensor", 10.0, 0.25).unwrap();
assert!(policy.evaluate(&10.25).is_accepted());
assert!(!policy.evaluate(&10.251).is_accepted());
assert!(!policy.evaluate(&f64::NAN).is_accepted());
}
#[test]
fn relative_tolerance_uses_absolute_floor_near_zero() {
let policy = Policy::relative_tolerance("zero", 0.0, 0.05, 0.01).unwrap();
assert!(policy.evaluate(&0.009).is_accepted());
assert!(!policy.evaluate(&0.011).is_accepted());
}
#[test]
fn inclusive_and_exclusive_ranges_have_clear_boundaries() {
let inclusive = Policy::inclusive_range("inclusive", 1, 3).unwrap();
let exclusive = Policy::exclusive_range("exclusive", 1, 3).unwrap();
assert!(inclusive.evaluate(&1).is_accepted());
assert!(!exclusive.evaluate(&1).is_accepted());
assert!(exclusive.evaluate(&2).is_accepted());
}
#[test]
fn all_evaluates_every_child_for_explanation() {
let positive = Policy::allow_if("positive", "must be positive", |v: &i32| *v > 0).unwrap();
let even = Policy::allow_if("even", "must be even", |v: &i32| *v % 2 == 0).unwrap();
let policy = Policy::all("valid number", [positive, even]).unwrap();
let result = policy.evaluate(&-3);
assert!(!result.is_accepted());
assert_eq!(result.children().len(), 2);
assert!(result.children().iter().all(|child| !child.is_accepted()));
}
#[test]
fn any_accepts_one_matching_child() {
let small = Policy::inclusive_range("small", 0, 10).unwrap();
let large = Policy::inclusive_range("large", 90, 100).unwrap();
let policy = Policy::any("edge", [small, large]).unwrap();
assert!(policy.evaluate(&95).is_accepted());
assert!(!policy.evaluate(&50).is_accepted());
}
#[test]
fn not_inverts_and_preserves_child_result() {
let empty = Policy::allow_if("empty", "must be empty", String::is_empty).unwrap();
let non_empty = empty.not("non-empty").unwrap();
let result = non_empty.evaluate(&"hello".to_owned());
assert!(result.is_accepted());
assert_eq!(result.children()[0].policy(), "empty");
}
#[test]
fn decision_walk_is_preorder() {
let a = Policy::allow_if("a", "a", |_: &()| true).unwrap();
let b = Policy::allow_if("b", "b", |_: &()| true).unwrap();
let root = Policy::all("root", [a, b]).unwrap().evaluate(&());
let names: Vec<_> = root.walk().map(Decision::policy).collect();
assert_eq!(names, ["root", "a", "b"]);
}
#[test]
fn invalid_policy_definitions_are_rejected() {
assert!(matches!(
Policy::<i32>::all("empty", []),
Err(Error::EmptyComposite)
));
assert!(matches!(
Policy::absolute_tolerance("bad", 1.0, -1.0),
Err(Error::InvalidTolerance(_))
));
assert!(matches!(
Policy::relative_tolerance("overflow", f64::MAX, 2.0, 0.0),
Err(Error::InvalidTolerance(_))
));
assert!(matches!(
Policy::inclusive_range("backwards", 3, 1),
Err(Error::ReversedRange)
));
}
}