Skip to main content

assert_rs/assertion/
binary.rs

1use super::{AssertInfo, Assertion, Debug, Display};
2
3/// An assertion about two objects `lhs` and `rhs`.
4#[must_use = "assertions do not fire unless returned from a test"]
5pub struct BinaryAssertion<T, U> {
6    lhs: T,
7    rhs: U,
8    test_result: bool,
9    test_repr: &'static str,
10    info: AssertInfo,
11}
12
13impl<T, U> Display for BinaryAssertion<T, U>
14where
15    T: Debug,
16    U: Debug,
17{
18    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
19        let Self {
20            lhs,
21            rhs,
22            test_result: _,
23            test_repr,
24            info: AssertInfo { file, line, column },
25        } = self;
26
27        write!(
28            f,
29            "assertion starting at {file}:{line}:{column} failed: `{test_repr}`\n lhs: {lhs:?}\n rhs: {rhs:?}"
30        )
31    }
32}
33
34impl<T, U> Debug for BinaryAssertion<T, U>
35where
36    T: Debug,
37    U: Debug,
38{
39    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
40        Display::fmt(self, f)
41    }
42}
43
44impl<T, U> BinaryAssertion<T, U> {
45    pub(crate) const fn new(
46        lhs: T,
47        rhs: U,
48        test_result: bool,
49        test_repr: &'static str,
50        info: AssertInfo,
51    ) -> Self {
52        Self {
53            lhs,
54            rhs,
55            test_result,
56            test_repr,
57            info,
58        }
59    }
60}
61
62#[cfg(feature = "std")]
63impl<T, U> std::process::Termination for BinaryAssertion<T, U>
64where
65    T: Debug,
66    U: Debug,
67{
68    fn report(self) -> std::process::ExitCode {
69        if self.test() {
70            std::process::ExitCode::SUCCESS
71        } else {
72            println!("{self}");
73            std::process::ExitCode::FAILURE
74        }
75    }
76}
77
78impl<T, U> Assertion for BinaryAssertion<T, U>
79where
80    T: Debug,
81    U: Debug,
82{
83    fn test(&self) -> bool {
84        self.test_result
85    }
86}