Skip to content

Commit

Permalink
Fix panic with custom Debug impl returning an empty string
Browse files Browse the repository at this point in the history
The panic was 'attempt to subtract with overflow' because
the first difference is addition.

PrettyString is from idubrov:
#24 (comment)
  • Loading branch information
nickolay authored and colin-kiegel committed Feb 15, 2019
1 parent 965f11b commit 4edb2ae
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/format_changeset.rs
Expand Up @@ -36,7 +36,8 @@ pub fn format_changeset(f: &mut fmt::Formatter, changeset: &Changeset) -> fmt::R
}
}
Difference::Add(ref added) => {
match diffs.get(i - 1) {
let prev = i.checked_sub(1).and_then(|x| diffs.get(x));
match prev {
Some(&Difference::Rem(ref removed)) => {
// The addition is preceded by an removal.
//
Expand All @@ -52,7 +53,8 @@ pub fn format_changeset(f: &mut fmt::Formatter, changeset: &Changeset) -> fmt::R
};
}
Difference::Rem(ref removed) => {
match diffs.get(i + 1) {
let next = i.checked_add(1).and_then(|x| diffs.get(x));
match next {
Some(&Difference::Add(_)) => {
// The removal is followed by an addition.
//
Expand Down
28 changes: 28 additions & 0 deletions tests/pretty_string.rs
@@ -0,0 +1,28 @@
#[macro_use]
extern crate pretty_assertions;

use std::fmt;
/// Wrapper around string slice that makes debug output `{:?}` to print string same way as `{}`.
/// Used in different `assert*!` macros in combination with `pretty_assertions` crate to make
/// test failures to show nice diffs.
#[derive(PartialEq, Eq)]
#[doc(hidden)]
pub struct PrettyString<'a>(pub &'a str);

/// Make diff to display string as multi-line string
impl<'a> fmt::Debug for PrettyString<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.0)
}
}

#[test]
#[should_panic(expected = r#"assertion failed: `(left == right)`
Diff < left / right > :
>foo

"#)]
fn assert_eq_empty_first() {
assert_eq!(PrettyString(""), PrettyString("foo"));
}

0 comments on commit 4edb2ae

Please sign in to comment.