use std::borrow::Cow;
use std::fmt;
use std::hash::Hash;
use crate::core::util::number::Number;
#[derive(Clone)]
pub struct Explanation {
matched: bool,
pub(crate) value: Number,
description: Cow<'static, str>,
details: Vec<Explanation>,
}
impl Explanation {
fn new<N, S>(matched: bool, value: N, description: S, details: Vec<Explanation>) -> Self
where
N: Into<Number>,
S: Into<Cow<'static, str>>,
{
Explanation {
matched,
value: value.into(),
description: description.into(),
details,
}
}
pub fn is_match(&self) -> bool {
self.matched
}
pub fn get_value(&self) -> &Number {
&self.value
}
pub fn get_description(&self) -> &str {
&self.description
}
fn get_summary<W: fmt::Write + ?Sized>(&self, buffer: &mut W) -> fmt::Result {
write!(buffer, "{} = {}", self.get_value(), self.get_description())
}
pub fn get_details(&self) -> &[Explanation] {
&self.details
}
fn to_string_with_depth<W: fmt::Write + ?Sized>(
&self,
depth: usize,
buffer: &mut W,
) -> fmt::Result {
for _ in 0..depth {
buffer.write_str(" ")?;
}
self.get_summary(buffer)?;
buffer.write_char('\n')?;
for detail in &self.details {
detail.to_string_with_depth(depth + 1, buffer)?;
}
Ok(())
}
pub fn match_no_details<N, S>(value: N, description: S) -> Explanation
where
N: Into<Number>,
S: Into<Cow<'static, str>>,
{
Self::match_(value, description, vec![])
}
pub fn match_<N, S, I>(value: N, description: S, details: I) -> Explanation
where
N: Into<Number>,
S: Into<Cow<'static, str>>,
I: IntoIterator<Item = Explanation>,
{
let details = details.into_iter().collect::<Vec<Explanation>>();
Explanation::new(true, value, description, details)
}
pub fn no_match_no_details<S>(description: S) -> Explanation
where
S: Into<Cow<'static, str>>,
{
Self::no_match(description, vec![])
}
pub fn no_match<S, I>(description: S, details: I) -> Explanation
where
S: Into<Cow<'static, str>>,
I: IntoIterator<Item = Explanation>,
{
let details = details.into_iter().collect::<Vec<Explanation>>();
Explanation::new(false, Number::F32(0.0), description, details)
}
pub fn error_explanation<S>(description: S) -> Explanation
where
S: Into<Cow<'static, str>>,
{
Explanation::match_no_details(0, description)
}
}
impl PartialEq for Explanation {
fn eq(&self, other: &Self) -> bool {
self.matched == other.matched
&& self.value == other.value
&& self.description == other.description
&& self.details == other.details
}
}
impl Hash for Explanation {
fn hash<H>(&self, state: &mut H)
where
H: std::hash::Hasher,
{
self.matched.hash(state);
self.value.hash(state);
self.description.hash(state);
self.details.hash(state);
}
}
impl Eq for Explanation {}
impl fmt::Display for Explanation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.to_string_with_depth(0, f)
}
}