Skip to content

Commit

Permalink
Automatically use StrComparison for comparing strings
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Mar 9, 2022
1 parent 7b5afed commit 94a570c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
35 changes: 34 additions & 1 deletion pretty_assertions/src/lib.rs
Expand Up @@ -239,6 +239,7 @@ macro_rules! assert_eq {
$crate::assert_eq!(@ $left, $right, ": ", $($arg)+);
});
(@ $left:expr, $right:expr, $maybe_semicolon:expr, $($arg:tt)*) => ({
use $crate::private::CreateComparison;
match (&($left), &($right)) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
Expand All @@ -248,7 +249,7 @@ macro_rules! assert_eq {
\n",
$maybe_semicolon,
format_args!($($arg)*),
$crate::Comparison::new(left_val, right_val)
(left_val, right_val).create_comparison()
)
}
}
Expand Down Expand Up @@ -430,3 +431,35 @@ macro_rules! assert_matches {
}
});
}

// Not public API. Used by the expansion of this crate's assert macros.
#[doc(hidden)]
pub mod private {
pub trait CompareAsStrByDefault: AsRef<str> {}
impl CompareAsStrByDefault for str {}
impl CompareAsStrByDefault for String {}
impl<T: CompareAsStrByDefault + ?Sized> CompareAsStrByDefault for &T {}

pub trait CreateComparison {
type Comparison;
fn create_comparison(self) -> Self::Comparison;
}

impl<'a, T, U> CreateComparison for &'a (T, U) {
type Comparison = crate::Comparison<'a, T, U>;
fn create_comparison(self) -> Self::Comparison {
crate::Comparison::new(&self.0, &self.1)
}
}

impl<'a, T, U> CreateComparison for (&'a T, &'a U)
where
T: CompareAsStrByDefault + ?Sized,
U: CompareAsStrByDefault + ?Sized,
{
type Comparison = crate::StrComparison<'a, T, U>;
fn create_comparison(self) -> Self::Comparison {
crate::StrComparison::new(self.0, self.1)
}
}
}
5 changes: 3 additions & 2 deletions pretty_assertions/tests/macros.rs
Expand Up @@ -166,8 +166,9 @@ mod assert_eq {
#[should_panic(expected = r#"assertion failed: `(left == right)`
Diff < left / right > :
<"foo\nbar"
>"foo\nbaz"
foo
<bar
>baz
"#)]
fn fails_str() {
Expand Down

0 comments on commit 94a570c

Please sign in to comment.