Skip to main content

ac_algorithm/
compare.rs

1//! Output comparison for local test runs (A-02, issue #25).
2//!
3//! [`compare`] applies an [`OutputComparator`] to captured program output
4//! and reports the first differing line so callers can render an
5//! expected-vs-actual diff. Comparison is byte-oriented and never invokes
6//! a judge checker; results stay [`LocalVerdict`](crate::verdict::LocalVerdict)
7//! territory, never official judge verdicts (ADR-0005 invariant 1).
8
9use crate::case::OutputComparator;
10
11/// Outcome of comparing actual output against an expected output.
12#[derive(Clone, Debug, PartialEq)]
13pub struct Comparison {
14    /// `true` when the comparator accepts the actual output.
15    pub matched: bool,
16    /// First differing line when `matched` is `false`.
17    pub first_diff: Option<DiffLine>,
18    /// Number of lines on each side, for display context.
19    pub expected_lines: usize,
20    /// See [`Self::expected_lines`].
21    pub actual_lines: usize,
22}
23
24/// One differing line pair (1-based line number, content without the
25/// trailing newline).
26#[derive(Clone, Debug, PartialEq, Eq)]
27pub struct DiffLine {
28    /// 1-based line number in the normalized expected output.
29    pub line: usize,
30    /// Expected line content, when the expected side has one.
31    pub expected: Option<String>,
32    /// Actual line content, when the actual side has one.
33    pub actual: Option<String>,
34}
35
36/// Compares `actual` against `expected` under `comparator`.
37///
38/// - [`OutputComparator::Exact`]: lines compared after trimming trailing
39///   whitespace; a missing final newline is insignificant.
40/// - [`OutputComparator::Tokenwise`]: whitespace-separated token streams
41///   must be identical.
42/// - [`OutputComparator::Float`]: token-wise like [`OutputComparator::Tokenwise`],
43///   but token pairs that both parse as `f64` match when their absolute
44///   difference is within `epsilon`; non-numeric tokens must be equal.
45#[must_use]
46pub fn compare(expected: &[u8], actual: &[u8], comparator: &OutputComparator) -> Comparison {
47    match comparator {
48        OutputComparator::Exact => compare_exact(expected, actual),
49        OutputComparator::Tokenwise => compare_tokens(expected, actual, None),
50        OutputComparator::Float { epsilon } => compare_tokens(expected, actual, Some(*epsilon)),
51    }
52}
53
54/// Normalizes text for exact comparison: per-line trailing whitespace is
55/// dropped and line terminators are unified. The final newline (or its
56/// absence) does not affect the result.
57fn normalized_lines(bytes: &[u8]) -> Vec<String> {
58    let text = String::from_utf8_lossy(bytes);
59    text.lines()
60        .map(|line| line.trim_end().to_owned())
61        .collect()
62}
63
64fn compare_exact(expected: &[u8], actual: &[u8]) -> Comparison {
65    let expected_lines = normalized_lines(expected);
66    let actual_lines = normalized_lines(actual);
67    let first_diff = first_line_diff(&expected_lines, &actual_lines);
68    Comparison {
69        matched: first_diff.is_none(),
70        first_diff,
71        expected_lines: expected_lines.len(),
72        actual_lines: actual_lines.len(),
73    }
74}
75
76fn tokens(bytes: &[u8]) -> Vec<String> {
77    String::from_utf8_lossy(bytes)
78        .split_whitespace()
79        .map(str::to_owned)
80        .collect()
81}
82
83fn compare_tokens(expected: &[u8], actual: &[u8], epsilon: Option<f64>) -> Comparison {
84    let expected_tokens = tokens(expected);
85    let actual_tokens = tokens(actual);
86    let len = expected_tokens.len().max(actual_tokens.len());
87    let mut first_diff = None;
88    for index in 0..len {
89        let (expected_token, actual_token) = (expected_tokens.get(index), actual_tokens.get(index));
90        let matched = match (expected_token, actual_token, epsilon) {
91            (Some(e), Some(a), Some(eps)) => match (e.parse::<f64>(), a.parse::<f64>()) {
92                (Ok(e), Ok(a)) => (e - a).abs() <= eps,
93                _ => e == a,
94            },
95            (Some(e), Some(a), None) => e == a,
96            _ => false,
97        };
98        if !matched {
99            first_diff = Some(DiffLine {
100                line: index + 1,
101                expected: expected_token.cloned(),
102                actual: actual_token.cloned(),
103            });
104            break;
105        }
106    }
107    Comparison {
108        matched: first_diff.is_none(),
109        first_diff,
110        expected_lines: expected_tokens.len(),
111        actual_lines: actual_tokens.len(),
112    }
113}
114
115/// First index where two line sequences differ, reported as a 1-based
116/// [`DiffLine`]. `None` when the sequences are identical.
117fn first_line_diff(expected: &[String], actual: &[String]) -> Option<DiffLine> {
118    let len = expected.len().max(actual.len());
119    for index in 0..len {
120        let (e, a) = (expected.get(index), actual.get(index));
121        if e != a {
122            return Some(DiffLine {
123                line: index + 1,
124                expected: e.cloned(),
125                actual: a.cloned(),
126            });
127        }
128    }
129    None
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    #[test]
137    fn exact_ignores_trailing_whitespace_and_final_newline() {
138        let expected = b"1 2\n3 4\n";
139        let actual = b"1 2  \n3 4";
140        let result = compare(expected, actual, &OutputComparator::Exact);
141        assert!(result.matched);
142    }
143
144    #[test]
145    fn exact_reports_first_differing_line() {
146        let expected = b"a\nb\nc\n";
147        let actual = b"a\nX\nc\n";
148        let result = compare(expected, actual, &OutputComparator::Exact);
149        assert!(!result.matched);
150        let diff = result.first_diff.expect("diff");
151        assert_eq!(diff.line, 2);
152        assert_eq!(diff.expected.as_deref(), Some("b"));
153        assert_eq!(diff.actual.as_deref(), Some("X"));
154    }
155
156    #[test]
157    fn tokenwise_ignores_layout() {
158        let expected = b"1 2 3\n4 5\n";
159        let actual = b"1\t2   3\n4\n5\n";
160        let result = compare(expected, actual, &OutputComparator::Tokenwise);
161        assert!(result.matched);
162    }
163
164    #[test]
165    fn tokenwise_detects_missing_token() {
166        let result = compare(b"1 2 3", b"1 2", &OutputComparator::Tokenwise);
167        assert!(!result.matched);
168        let diff = result.first_diff.expect("diff");
169        assert_eq!(diff.line, 3);
170        assert_eq!(diff.expected.as_deref(), Some("3"));
171        assert_eq!(diff.actual, None);
172    }
173
174    #[test]
175    fn float_respects_epsilon() {
176        let comparator = OutputComparator::Float { epsilon: 1e-6 };
177        assert!(compare(b"0.1", b"0.1000005", &comparator).matched);
178        assert!(!compare(b"0.1", b"0.2", &comparator).matched);
179        // Non-numeric tokens still require exact equality.
180        assert!(compare(b"ok 1.0", b"ok 1.0000001", &comparator).matched);
181        assert!(!compare(b"ok 1.0", b"ng 1.0", &comparator).matched);
182    }
183}