assert-rs 0.1.1

An assertion library that uses types and data to fail tests instead of panicking.
Documentation
use super::{AssertInfo, Assertion, Debug, Display};

/// An assertion about an object `this`.
#[must_use = "assertions do not fire unless returned from a test"]
pub struct UnaryAssertion<T> {
    this: T,
    test_result: bool,
    test_repr: &'static str,
    info: AssertInfo,
}

impl<T> Display for UnaryAssertion<T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let Self {
            this,
            test_result: _,
            test_repr,
            info: AssertInfo { file, line, column },
        } = self;

        write!(
            f,
            "assertion starting at {file}:{line}:{column} failed: `{test_repr}`\nthis: {this:?}"
        )
    }
}

impl<T> Debug for UnaryAssertion<T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        Display::fmt(self, f)
    }
}

impl<T> UnaryAssertion<T> {
    pub(crate) const fn new(
        this: T,
        test_result: bool,
        test_repr: &'static str,
        info: AssertInfo,
    ) -> Self {
        Self {
            this,
            test_result,
            test_repr,
            info,
        }
    }
}

#[cfg(feature = "std")]
impl<T> std::process::Termination for UnaryAssertion<T>
where
    T: Debug,
{
    fn report(self) -> std::process::ExitCode {
        if self.test() {
            std::process::ExitCode::SUCCESS
        } else {
            println!("{self}");
            std::process::ExitCode::FAILURE
        }
    }
}

impl<T> Assertion for UnaryAssertion<T>
where
    T: Debug,
{
    fn test(&self) -> bool {
        self.test_result
    }
}