stefans_utils/
expect_comparison.rs

1use crate::comparator::Comparison;
2use core::{error::Error, fmt};
3
4pub trait ExpectComparison: PartialOrd + PartialEq + Sized {
5    fn expect_lt(self, other: Self) -> Result<Self, ExpectedComparisonError<Self>>;
6    fn expect_lte(self, other: Self) -> Result<Self, ExpectedComparisonError<Self>>;
7    fn expect_eq(self, other: Self) -> Result<Self, ExpectedComparisonError<Self>>;
8    fn expect_ne(self, other: Self) -> Result<Self, ExpectedComparisonError<Self>>;
9    fn expect_gte(self, other: Self) -> Result<Self, ExpectedComparisonError<Self>>;
10    fn expect_gt(self, other: Self) -> Result<Self, ExpectedComparisonError<Self>>;
11}
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
15#[cfg_attr(feature = "schemars", derive(::schemars::JsonSchema))]
16pub struct ExpectedComparisonError<T> {
17    pub comparison: Comparison,
18    pub comparator: T,
19    pub actual: T,
20}
21
22impl<T: fmt::Debug> Error for ExpectedComparisonError<T> {}
23
24impl<T: fmt::Debug> fmt::Display for ExpectedComparisonError<T> {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        f.write_fmt(format_args!(
27            "Expected value to be {} {:?}, but it was {:?}",
28            self.comparison, self.comparator, self.actual
29        ))
30    }
31}
32
33impl Comparison {
34    pub fn expect_comparison<T: PartialOrd + PartialEq>(
35        &self,
36        actual: T,
37        comparator: T,
38    ) -> Result<T, ExpectedComparisonError<T>> {
39        if self.compare(&actual, &comparator) {
40            Ok(actual)
41        } else {
42            Err(ExpectedComparisonError {
43                comparison: *self,
44                comparator,
45                actual,
46            })
47        }
48    }
49}
50
51impl<T: PartialOrd + PartialEq + Sized> ExpectComparison for T {
52    fn expect_lt(self, other: Self) -> Result<Self, ExpectedComparisonError<Self>> {
53        Comparison::Less.expect_comparison(self, other)
54    }
55
56    fn expect_lte(self, other: Self) -> Result<Self, ExpectedComparisonError<Self>> {
57        Comparison::LessOrEqual.expect_comparison(self, other)
58    }
59
60    fn expect_eq(self, other: Self) -> Result<Self, ExpectedComparisonError<Self>> {
61        Comparison::Equal.expect_comparison(self, other)
62    }
63
64    fn expect_ne(self, other: Self) -> Result<Self, ExpectedComparisonError<Self>> {
65        Comparison::Unequal.expect_comparison(self, other)
66    }
67
68    fn expect_gte(self, other: Self) -> Result<Self, ExpectedComparisonError<Self>> {
69        Comparison::GreaterOrEqual.expect_comparison(self, other)
70    }
71
72    fn expect_gt(self, other: Self) -> Result<Self, ExpectedComparisonError<Self>> {
73        Comparison::Greater.expect_comparison(self, other)
74    }
75}