ac-algorithm 0.2.0

Algorithm competition domain logic for ac
Documentation
//! Output comparison for local test runs (A-02, issue #25).
//!
//! [`compare`] applies an [`OutputComparator`] to captured program output
//! and reports the first differing line so callers can render an
//! expected-vs-actual diff. Comparison is byte-oriented and never invokes
//! a judge checker; results stay [`LocalVerdict`](crate::verdict::LocalVerdict)
//! territory, never official judge verdicts (ADR-0005 invariant 1).

use crate::case::OutputComparator;

/// Outcome of comparing actual output against an expected output.
#[derive(Clone, Debug, PartialEq)]
pub struct Comparison {
    /// `true` when the comparator accepts the actual output.
    pub matched: bool,
    /// First differing line when `matched` is `false`.
    pub first_diff: Option<DiffLine>,
    /// Number of lines on each side, for display context.
    pub expected_lines: usize,
    /// See [`Self::expected_lines`].
    pub actual_lines: usize,
}

/// One differing line pair (1-based line number, content without the
/// trailing newline).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DiffLine {
    /// 1-based line number in the normalized expected output.
    pub line: usize,
    /// Expected line content, when the expected side has one.
    pub expected: Option<String>,
    /// Actual line content, when the actual side has one.
    pub actual: Option<String>,
}

/// Compares `actual` against `expected` under `comparator`.
///
/// - [`OutputComparator::Exact`]: lines compared after trimming trailing
///   whitespace; a missing final newline is insignificant.
/// - [`OutputComparator::Tokenwise`]: whitespace-separated token streams
///   must be identical.
/// - [`OutputComparator::Float`]: token-wise like [`OutputComparator::Tokenwise`],
///   but token pairs that both parse as `f64` match when their absolute
///   difference is within `epsilon`; non-numeric tokens must be equal.
#[must_use]
pub fn compare(expected: &[u8], actual: &[u8], comparator: &OutputComparator) -> Comparison {
    match comparator {
        OutputComparator::Exact => compare_exact(expected, actual),
        OutputComparator::Tokenwise => compare_tokens(expected, actual, None),
        OutputComparator::Float { epsilon } => compare_tokens(expected, actual, Some(*epsilon)),
    }
}

/// Normalizes text for exact comparison: per-line trailing whitespace is
/// dropped and line terminators are unified. The final newline (or its
/// absence) does not affect the result.
fn normalized_lines(bytes: &[u8]) -> Vec<String> {
    let text = String::from_utf8_lossy(bytes);
    text.lines()
        .map(|line| line.trim_end().to_owned())
        .collect()
}

fn compare_exact(expected: &[u8], actual: &[u8]) -> Comparison {
    let expected_lines = normalized_lines(expected);
    let actual_lines = normalized_lines(actual);
    let first_diff = first_line_diff(&expected_lines, &actual_lines);
    Comparison {
        matched: first_diff.is_none(),
        first_diff,
        expected_lines: expected_lines.len(),
        actual_lines: actual_lines.len(),
    }
}

fn tokens(bytes: &[u8]) -> Vec<String> {
    String::from_utf8_lossy(bytes)
        .split_whitespace()
        .map(str::to_owned)
        .collect()
}

fn compare_tokens(expected: &[u8], actual: &[u8], epsilon: Option<f64>) -> Comparison {
    let expected_tokens = tokens(expected);
    let actual_tokens = tokens(actual);
    let len = expected_tokens.len().max(actual_tokens.len());
    let mut first_diff = None;
    for index in 0..len {
        let (expected_token, actual_token) = (expected_tokens.get(index), actual_tokens.get(index));
        let matched = match (expected_token, actual_token, epsilon) {
            (Some(e), Some(a), Some(eps)) => match (e.parse::<f64>(), a.parse::<f64>()) {
                (Ok(e), Ok(a)) => (e - a).abs() <= eps,
                _ => e == a,
            },
            (Some(e), Some(a), None) => e == a,
            _ => false,
        };
        if !matched {
            first_diff = Some(DiffLine {
                line: index + 1,
                expected: expected_token.cloned(),
                actual: actual_token.cloned(),
            });
            break;
        }
    }
    Comparison {
        matched: first_diff.is_none(),
        first_diff,
        expected_lines: expected_tokens.len(),
        actual_lines: actual_tokens.len(),
    }
}

/// First index where two line sequences differ, reported as a 1-based
/// [`DiffLine`]. `None` when the sequences are identical.
fn first_line_diff(expected: &[String], actual: &[String]) -> Option<DiffLine> {
    let len = expected.len().max(actual.len());
    for index in 0..len {
        let (e, a) = (expected.get(index), actual.get(index));
        if e != a {
            return Some(DiffLine {
                line: index + 1,
                expected: e.cloned(),
                actual: a.cloned(),
            });
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn exact_ignores_trailing_whitespace_and_final_newline() {
        let expected = b"1 2\n3 4\n";
        let actual = b"1 2  \n3 4";
        let result = compare(expected, actual, &OutputComparator::Exact);
        assert!(result.matched);
    }

    #[test]
    fn exact_reports_first_differing_line() {
        let expected = b"a\nb\nc\n";
        let actual = b"a\nX\nc\n";
        let result = compare(expected, actual, &OutputComparator::Exact);
        assert!(!result.matched);
        let diff = result.first_diff.expect("diff");
        assert_eq!(diff.line, 2);
        assert_eq!(diff.expected.as_deref(), Some("b"));
        assert_eq!(diff.actual.as_deref(), Some("X"));
    }

    #[test]
    fn tokenwise_ignores_layout() {
        let expected = b"1 2 3\n4 5\n";
        let actual = b"1\t2   3\n4\n5\n";
        let result = compare(expected, actual, &OutputComparator::Tokenwise);
        assert!(result.matched);
    }

    #[test]
    fn tokenwise_detects_missing_token() {
        let result = compare(b"1 2 3", b"1 2", &OutputComparator::Tokenwise);
        assert!(!result.matched);
        let diff = result.first_diff.expect("diff");
        assert_eq!(diff.line, 3);
        assert_eq!(diff.expected.as_deref(), Some("3"));
        assert_eq!(diff.actual, None);
    }

    #[test]
    fn float_respects_epsilon() {
        let comparator = OutputComparator::Float { epsilon: 1e-6 };
        assert!(compare(b"0.1", b"0.1000005", &comparator).matched);
        assert!(!compare(b"0.1", b"0.2", &comparator).matched);
        // Non-numeric tokens still require exact equality.
        assert!(compare(b"ok 1.0", b"ok 1.0000001", &comparator).matched);
        assert!(!compare(b"ok 1.0", b"ng 1.0", &comparator).matched);
    }
}