use alloc::{
borrow::Cow,
string::{
String,
ToString,
},
};
use core::fmt;
use crate::errors::{
BunsenError,
BunsenErrorKind,
};
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Rule {
ZeroOrEmpty,
OutOfRange {
value: String,
range: String,
},
NotMultiple {
value: usize,
of: String,
},
Relation {
lhs: (String, String),
op: &'static str,
rhs: (String, String),
},
Chain {
index: usize,
out: String,
r#in: String,
},
Missing,
State {
expected: &'static str,
},
Custom(String),
}
impl fmt::Display for Rule {
fn fmt(
&self,
f: &mut fmt::Formatter<'_>,
) -> fmt::Result {
match self {
Self::ZeroOrEmpty => f.write_str("must not be zero or empty"),
Self::OutOfRange { value, range } => {
write!(f, "{value} is outside {range}")
}
Self::NotMultiple { value, of } => {
write!(f, "{value} is not a multiple of {of}")
}
Self::Relation { lhs, op, rhs } => write!(
f,
"{} ({}) must be {op} {} ({})",
lhs.0, lhs.1, rhs.0, rhs.1
),
Self::Chain { index, out, r#in } => write!(
f,
"stage {index} takes {}, but the stage before it puts out {}",
r#in, out
),
Self::Missing => f.write_str("is required"),
Self::State { expected } => write!(f, "must be {expected}"),
Self::Custom(text) => f.write_str(text),
}
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConstraintError {
pub owner: &'static str,
pub field: Cow<'static, str>,
pub rule: Rule,
}
impl ConstraintError {
pub fn new(
owner: &'static str,
field: impl Into<Cow<'static, str>>,
rule: Rule,
) -> Self {
Self {
owner,
field: field.into(),
rule,
}
}
pub fn out_of_range(
owner: &'static str,
field: impl Into<Cow<'static, str>>,
value: impl fmt::Display,
range: impl fmt::Display,
) -> Self {
Self::new(
owner,
field,
Rule::OutOfRange {
value: value.to_string(),
range: range.to_string(),
},
)
}
pub fn zero_or_empty(
owner: &'static str,
field: impl Into<Cow<'static, str>>,
) -> Self {
Self::new(owner, field, Rule::ZeroOrEmpty)
}
pub fn custom(
owner: &'static str,
field: impl Into<Cow<'static, str>>,
text: impl fmt::Display,
) -> Self {
Self::new(owner, field, Rule::Custom(text.to_string()))
}
}
impl fmt::Display for ConstraintError {
fn fmt(
&self,
f: &mut fmt::Formatter<'_>,
) -> fmt::Result {
if self.field.is_empty() {
write!(f, "{}: {}", self.owner, self.rule)
} else {
write!(f, "{}.{}: {}", self.owner, self.field, self.rule)
}
}
}
impl core::error::Error for ConstraintError {}
impl From<ConstraintError> for BunsenError {
#[track_caller]
fn from(error: ConstraintError) -> Self {
BunsenError::from_cause(BunsenErrorKind::Illegal, error)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_display() {
assert_eq!(
ConstraintError::out_of_range("Relaxation", "omega", 2.5, "(0, 2)").to_string(),
"Relaxation.omega: 2.5 is outside (0, 2)"
);
assert_eq!(
ConstraintError::new(
"SlidingStftConfig",
"",
Rule::Relation {
lhs: ("hop".into(), "512".into()),
op: "<=",
rhs: ("window".into(), "400".into()),
}
)
.to_string(),
"SlidingStftConfig: hop (512) must be <= window (400)"
);
}
#[test]
fn test_kind() {
let e: BunsenError = ConstraintError::zero_or_empty("X", "y").into();
assert_eq!(e.kind(), BunsenErrorKind::Illegal);
assert_eq!(e.find::<ConstraintError>().unwrap().field, "y");
}
}