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 c1b329a commit edc4533
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
38 changes: 37 additions & 1 deletion pretty_assertions/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,13 +242,14 @@ macro_rules! assert_eq {
match (&($left), &($right)) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
use $crate::private::CreateComparison;
::core::panic!("assertion failed: `(left == right)`{}{}\
\n\
\n{}\
\n",
$maybe_colon,
format_args!($($arg)*),
$crate::Comparison::new(left_val, right_val)
(left_val, right_val).create_comparison()
)
}
}
Expand Down Expand Up @@ -430,3 +431,38 @@ macro_rules! assert_matches {
}
});
}

// Not public API. Used by the expansion of this crate's assert macros.
#[doc(hidden)]
pub mod private {
#[cfg(feature = "alloc")]
use alloc::string::String;

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
Original file line number Diff line number Diff line change
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 edc4533

Please sign in to comment.