icedwright-trace 0.0.1

The icedwright trace format: a deterministic .iwtrace archive of every step a test took, with its writer, reader and comparison
Documentation
//! The comparison the determinism check uses: every member byte for byte except `real.json`.

use core::fmt;
use std::collections::BTreeSet;

use crate::archive;
use crate::error::TraceError;
use crate::ids::StepIndex;
use crate::reader::TraceReader;

/// Where two traces first differ.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Difference {
    /// A step's record differs, or only one trace has it.
    Step(StepDifference),
    /// The steps match but `meta.json` does not.
    Meta,
    /// The steps and metadata match but this member differs or is only in one trace.
    Member(String),
}

/// The first step at which two traces differ.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StepDifference {
    /// The step.
    pub index: StepIndex,
    /// How it differs.
    pub change: StepChange,
}

/// How a step differs between two traces.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StepChange {
    /// Both traces have it, with different records.
    Changed,
    /// Only the first trace has it.
    OnlyInFirst,
    /// Only the second trace has it.
    OnlyInSecond,
}

impl fmt::Display for Difference {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Difference::Step(StepDifference { index, change }) => match change {
                StepChange::Changed => write!(f, "{index} differs"),
                StepChange::OnlyInFirst => write!(f, "{index} is only in the first trace"),
                StepChange::OnlyInSecond => write!(f, "{index} is only in the second trace"),
            },
            Difference::Meta => write!(f, "{} differs", archive::META),
            Difference::Member(name) => write!(f, "member {name} differs"),
        }
    }
}

/// Compares two traces member by member, skipping `real.json`, and reports the first step
/// that differs, then the metadata, then any other member by name. `None` means they are the
/// same apart from real timings.
pub fn compare(a: &TraceReader, b: &TraceReader) -> Result<Option<Difference>, TraceError> {
    let steps_a = a.member(archive::STEPS)?.unwrap_or_default();
    let steps_b = b.member(archive::STEPS)?.unwrap_or_default();
    if let Some(step) = first_differing_line(&steps_a, &steps_b) {
        return Ok(Some(Difference::Step(step)));
    }
    if a.member(archive::META)? != b.member(archive::META)? {
        return Ok(Some(Difference::Meta));
    }
    let skipped = [archive::STEPS, archive::META, archive::REAL];
    let names: BTreeSet<String> = a
        .members()
        .into_iter()
        .chain(b.members())
        .filter(|name| !skipped.contains(&name.as_str()))
        .collect();
    for name in names {
        if a.member(&name)? != b.member(&name)? {
            return Ok(Some(Difference::Member(name)));
        }
    }
    Ok(None)
}

fn first_differing_line(a: &[u8], b: &[u8]) -> Option<StepDifference> {
    let lines = |bytes: &'_ [u8]| -> Vec<Vec<u8>> {
        bytes
            .split(|byte| *byte == b'\n')
            .filter(|line| !line.is_empty())
            .map(<[u8]>::to_vec)
            .collect()
    };
    let (a, b) = (lines(a), lines(b));
    let length = a.len().max(b.len());
    (0..length).find_map(|position| {
        let change = match (a.get(position), b.get(position)) {
            (Some(x), Some(y)) if x == y => return None,
            (Some(_), Some(_)) => StepChange::Changed,
            (Some(_), None) => StepChange::OnlyInFirst,
            (None, _) => StepChange::OnlyInSecond,
        };
        Some(StepDifference {
            index: StepIndex::from_index(u32::try_from(position).unwrap_or(u32::MAX)),
            change,
        })
    })
}