1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
use std::fmt;

/// Created from two different strings.
/// Presents the difference when formatted.
pub struct Diff<'src, 'fmt> {
    source: &'src str,
    formatted: &'fmt str,
}

impl<'src, 'fmt> Diff<'src, 'fmt> {
    pub fn from(source: &'src str, formatted: &'fmt str) -> Option<Self> {
        if source != formatted {
            Some(Self { source, formatted })
        } else {
            None
        }
    }
}

impl<'src, 'fmt> fmt::Display for Diff<'src, 'fmt> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        f.write_str("Difference found.\n")?;
        f.write_str("Source:\n")?;
        f.write_str(&self.source)?;
        f.write_str("\n")?;
        f.write_str("Formatted:\n")?;
        f.write_str(&self.formatted)
    }
}

#[cfg(test)]
mod test {
    use super::Diff;
    use unindent::Unindent;

    #[test]
    fn check_should_return_none_for_no_diff() {
        let result = Diff::from("foo", "foo");
        assert!(matches!(result, None));
    }

    #[test]
    fn check_should_return_some_for_some_diff() {
        let result = Diff::from("foo", "bar");
        assert!(matches!(result, Some(..)));
    }

    #[test]
    fn diff_should_display_source_and_formatted() {
        let diff = Diff::from("foo", "bar").unwrap();
        let result = format!("{}", diff);
        assert_eq!(
            result,
            "
            Difference found.
            Source:
            foo
            Formatted:
            bar
            "
            .trim()
            .unindent()
        );
    }
}