icedwright-trace 0.0.2

The icedwright trace format: a deterministic .iwtrace archive of every step a test took, with its writer, reader and comparison
Documentation
//! Rewrites of text that would otherwise differ between runs, and the limits on its size.

use std::time::{Duration, Instant};

use icedwright_types::VirtualDuration;

/// The longest message `Debug` text kept, in bytes.
pub(crate) const MESSAGE_LIMIT: usize = 4 * 1024;

/// The largest state `Debug` text diffed, in bytes.
pub(crate) const STATE_LIMIT: usize = 256 * 1024;

/// The real instant the harness booted at, as the platform's `Instant` `Debug` text spells it,
/// so instants printed inside message text can be rewritten as offsets from boot.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BootInstant(Duration);

impl BootInstant {
    /// Reads `instant`'s `Debug` form, or `None` on a platform that prints it without
    /// `tv_sec` and `tv_nsec`.
    #[must_use]
    pub fn from_std(instant: &Instant) -> Option<Self> {
        Self::from_debug(&format!("{instant:?}"))
    }

    /// Reads an `Instant` `Debug` text such as `Instant { tv_sec: 5, tv_nsec: 20 }`.
    #[must_use]
    pub fn from_debug(text: &str) -> Option<Self> {
        let body = text.trim().strip_prefix("Instant")?;
        stamp(body).map(Self)
    }
}

/// The `tv_sec` and `tv_nsec` fields anywhere in `body`, as a duration.
fn stamp(body: &str) -> Option<Duration> {
    let secs = field(body, "tv_sec:")?;
    let nanos = field(body, "tv_nsec:")?;
    Some(Duration::new(secs, u32::try_from(nanos).ok()?))
}

fn field(body: &str, name: &str) -> Option<u64> {
    let start = body.find(name)? + name.len();
    let rest = body.get(start..)?.trim_start();
    let end = rest
        .find(|c: char| !c.is_ascii_digit())
        .unwrap_or(rest.len());
    rest.get(..end)?.parse().ok()
}

/// Replaces every `Instant { .. }` that holds `tv_sec` and `tv_nsec` with `@+<offset>` from
/// `boot`, or `@-<offset>` for one before it. Nested forms such as tokio's
/// `Instant { std: Instant { .. } }` are replaced whole.
pub(crate) fn rewrite_instants(text: &str, boot: BootInstant) -> String {
    let mut out = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(found) = rest.find("Instant") {
        let (before, from) = rest.split_at(found);
        out.push_str(before);
        let follows_word = before
            .chars()
            .next_back()
            .is_some_and(|c| c.is_alphanumeric() || c == '_');
        let replaced = (!follows_word)
            .then(|| braced(&from["Instant".len()..]))
            .flatten()
            .and_then(|(body, len)| stamp(body).map(|at| (at, len)));
        let Some((at, len)) = replaced else {
            out.push_str("Instant");
            rest = &from["Instant".len()..];
            continue;
        };
        match at.checked_sub(boot.0) {
            Some(after) => out.push_str(&format!("@+{}", VirtualDuration::from(after))),
            None => out.push_str(&format!("@-{}", VirtualDuration::from(boot.0 - at))),
        }
        rest = &from["Instant".len() + len..];
    }
    out.push_str(rest);
    out
}

/// The balanced `{ .. }` at the start of `text` after optional spaces: its contents and the
/// length consumed.
fn braced(text: &str) -> Option<(&str, usize)> {
    let open = text.len() - text.trim_start().len();
    if !text.get(open..)?.starts_with('{') {
        return None;
    }
    let mut depth = 0usize;
    for (offset, c) in text.get(open..)?.char_indices() {
        match c {
            '{' => depth += 1,
            '}' => {
                depth -= 1;
                if depth == 0 {
                    let end = open + offset;
                    return Some((text.get(open + 1..end)?, end + 1));
                }
            }
            _ => {}
        }
    }
    None
}

/// `text` cut to at most `limit` bytes on a character boundary, with the original length when
/// it was cut.
pub(crate) fn truncate(mut text: String, limit: usize) -> (String, Option<u64>) {
    if text.len() <= limit {
        return (text, None);
    }
    let full = u64::try_from(text.len()).unwrap_or(u64::MAX);
    let mut end = limit;
    while !text.is_char_boundary(end) {
        end -= 1;
    }
    text.truncate(end);
    (text, Some(full))
}

/// A unified line diff from `before` to `after`, `None` when they are equal, or a note when
/// either is larger than [`STATE_LIMIT`].
pub(crate) fn state_diff(before: &str, after: &str) -> Option<String> {
    if before == after {
        return None;
    }
    let largest = before.len().max(after.len());
    if largest > STATE_LIMIT {
        return Some(format!(
            "state Debug output is {largest} bytes, over the {} KiB limit, so no diff is kept",
            STATE_LIMIT / 1024
        ));
    }
    Some(
        similar::TextDiff::from_lines(before, after)
            .unified_diff()
            .context_radius(3)
            .header("before", "after")
            .to_string(),
    )
}

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

    fn boot() -> Option<BootInstant> {
        BootInstant::from_debug("Instant { tv_sec: 100, tv_nsec: 500000000 }")
    }

    #[test]
    fn boot_reads_the_debug_form() {
        assert_eq!(boot(), Some(BootInstant(Duration::new(100, 500_000_000))));
        assert_eq!(BootInstant::from_debug("Instant { t: 12 }"), None);
        assert_eq!(
            BootInstant::from_debug("Moment { tv_sec: 1, tv_nsec: 2 }"),
            None
        );
    }

    #[test]
    fn instants_become_offsets_from_boot() {
        let Some(boot) = boot() else {
            panic!("boot did not parse");
        };
        let text = "Tick(Instant { tv_sec: 101, tv_nsec: 750000000 }, Instant { tv_sec: 100, tv_nsec: 500000000 })";
        assert_eq!(rewrite_instants(text, boot), "Tick(@+1.250s, @+0.000s)");
    }

    #[test]
    fn pretty_and_nested_instants_are_rewritten_whole() {
        let Some(boot) = boot() else {
            panic!("boot did not parse");
        };
        let pretty =
            "Tick(\n    Instant {\n        tv_sec: 102,\n        tv_nsec: 500000000,\n    },\n)";
        assert_eq!(rewrite_instants(pretty, boot), "Tick(\n    @+2.000s,\n)");
        let tokio = "At(Instant { std: Instant { tv_sec: 100, tv_nsec: 600000000 } })";
        assert_eq!(rewrite_instants(tokio, boot), "At(@+0.100s)");
        let early = "Instant { tv_sec: 100, tv_nsec: 0 }";
        assert_eq!(rewrite_instants(early, boot), "@-0.500s");
    }

    #[test]
    fn other_text_is_left_alone() {
        let Some(boot) = boot() else {
            panic!("boot did not parse");
        };
        let cases = [
            "Saved(\"Instant\")",
            "LastInstant { tv_sec: 1, tv_nsec: 2 }",
            "Instant { label: 3 }",
            "Instant { tv_sec: 1",
            "Id(3) and Instant",
        ];
        for text in cases {
            assert_eq!(rewrite_instants(text, boot), text);
        }
    }

    #[test]
    fn truncation_respects_character_boundaries() {
        assert_eq!(truncate("short".to_owned(), 8), ("short".to_owned(), None));
        assert_eq!(
            truncate("abcdef".to_owned(), 4),
            ("abcd".to_owned(), Some(6))
        );
        assert_eq!(truncate("aƩ".to_owned(), 2), ("a".to_owned(), Some(3)));
    }

    #[test]
    fn state_diffs_are_unified_and_limited() {
        assert_eq!(state_diff("same", "same"), None);
        let before = "State {\n    count: 1,\n    name: \"a\",\n}\n";
        let after = "State {\n    count: 2,\n    name: \"a\",\n}\n";
        assert_eq!(
            state_diff(before, after).as_deref(),
            Some(
                "--- before\n+++ after\n@@ -1,4 +1,4 @@\n State {\n-    count: 1,\n+    count: 2,\n     name: \"a\",\n }\n"
            )
        );
        let huge = "x".repeat(STATE_LIMIT + 1);
        let note = state_diff("", &huge).unwrap_or_default();
        assert!(note.contains("over the 256 KiB limit"), "{note}");
    }
}