// SPDX-License-Identifier: MIT //! The board's gates as functions, so another board can run them on its own chips. //! //! The Atari 7800 board runs the whole 2600 in its 2600 mode, with its own TIA and //! RIOT objects (they have served its BIOS first) and its own clocking. These are //! the judges this repository passes, callable from outside (docs/api.md). Each //! takes `root`, an a2600-python checkout whose references are fetched //! (`python scripts/fetch_references.py` there) and whose locally recorded die traces //! and test ROMs sit where its scripts put them; romsets come from //! `NO_INTRO_DIR` as everywhere else. The candidate is supplied as a factory: //! //! - `tia_factory()`: a fresh TIA for a die-trace replay (the die gate); //! - `system_factory(cartridge, machine)`: a [`System`], for the timer //! ROMs, the serial tables, frame hashes and lockstep: powered on, or built //! on handed-in chips and a CPU that has been running //! ([`System::with_cpu`] on `Board::new(.., tia, riot, cycles)`), as a //! host's 2600 mode starts. //! //! Nothing here changes what the 2600 does: the tests and tools of this //! repository call the same functions with the default factories. //! //! Rust-forced differences (a2600-python `gates.py` at 28fb095): factories are //! closures; `serial_record` watches SWCHA through a bus observer filtered to //! the RIOT's writes (Python wraps `riot.write`; the observer runs after the //! write, as the wrapper's check did); `run_hashes` chains the TIA's line //! callback through shared cells; results are ordered maps; a ROM for //! `lockstep` is its bytes. use std::cell::RefCell; use std::collections::BTreeMap; use std::io::Read; use std::path::{Path, PathBuf}; use std::rc::Rc; use sha2::{Digest, Sha256}; use crate::cartridge::connector::Cartridge; use crate::cartridge::{load, load_default, mame_hash, Options, Rom}; use crate::machine::Machine; use crate::system::System; use crate::tia::TIA; /// `system_factory(cartridge, machine)`. pub type SystemFactory<'a> = &'a dyn Fn(Box, Machine) -> System; /// The default factory: `System(cartridge, machine)`. pub fn default_system(cartridge: Box, machine: Machine) -> System { System::new(cartridge, machine, None).expect("a machine row on its grid") } fn zip_member(archive: &Path, member: &str) -> Result, String> { let file = std::fs::File::open(archive).map_err(|e| format!("{}: {e}", archive.display()))?; let mut zip = zip::ZipArchive::new(file).map_err(|e| e.to_string())?; let mut data = Vec::new(); zip.by_name(member) .map_err(|e| format!("{member}: {e}"))? .read_to_end(&mut data) .map_err(|e| e.to_string())?; Ok(data) } // -- the die: Sim2600 traces replayed pin by pin -------------------------------- // The trace format: DOC: tia-fpga sim/README.md (gen_trace.py's columns). pub const PINS: [&str; 9] = ["ph0", "rdy", "sync", "lum", "col", "blank", "dbdrv", "au0", "au1"]; pub const COLUMNS: [&str; 17] = [ "clk0", "clk2", "rw", "cs0", "cs3", "ab", "db", "inpt", "ph0", "rdy", "sync", "lum", "col", "blank", "au0", "au1", "dbdrv", ]; /// Where the board follows hardware over the die, the half clocks it differs /// by, exactly: hmove_cycles' two HMOVEs on cycle 74, where seven consoles set /// the comb latch and Sim2600 clears it (docs/undocumented-behavior.md C27); /// hmove_resp0 has the same tie in its HMOVE-on-cycle-74 block. pub fn known_departures(name: &str) -> BTreeMap { let table: &[(&str, u64)] = match name { "hmove_cycles.trace" => &[("lum", 230), ("col", 220), ("blank", 32)], "hmove_resp0.trace" => &[("lum", 2638), ("col", 2638), ("blank", 352)], _ => &[], }; table.iter().map(|(p, n)| (p.to_string(), *n)).collect() } /// A die trace's records, one row of hex fields per half clock (`COLUMNS`). pub fn load_trace(path: &Path) -> Result>, String> { let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; let mut records = Vec::new(); for line in text.lines() { if line.starts_with('#') || line.trim().is_empty() { continue; } let row: Result, _> = line.split_whitespace().map(|v| u32::from_str_radix(v, 16)).collect(); records.push(row.map_err(|e| e.to_string())?); } Ok(records) } /// With the console's wiring CLK2 falls one record after PH0 falls. pub fn console_wiring(records: &[Vec]) -> bool { let end = records.len().min(20000); let votes = (1..end) .filter(|&k| records[k - 1][1] == 1 && records[k][1] == 0 && records[k - 1][8] == 0) .count(); let falls = (1..end) .filter(|&k| records[k - 1][1] != 0 && records[k][1] == 0) .count(); votes > falls / 2 } /// (records scored, mismatches per pin, first mismatch per pin, console wiring). pub type Replay = (u64, BTreeMap, BTreeMap, bool); /// The recorded inputs go into a fresh TIA from `tia_factory` and every /// output pin is compared at every half clock (the reference's /// scripts/die_trace.py has the rules: writes land where CLK2 falls; scoring /// starts at the first HBLANK rise after record `warm`). pub fn replay_trace( records: &[Vec], warm: usize, audio: bool, report: usize, stop_after: Option, tia_factory: &mut dyn FnMut() -> TIA, ) -> Result { let console = console_wiring(records); let mut tia = tia_factory(); tia.rising = records[0][0] == 1; let start = (warm.max(1)..records.len()) .find(|&k| records[k][13] != 0 && records[k - 1][13] == 0) .unwrap_or(records.len()); let mut mismatches: BTreeMap = PINS.iter().map(|p| (p.to_string(), 0)).collect(); let mut first: BTreeMap = BTreeMap::new(); let mut shown = 0; let mut bus = &records[0]; // the bus as the die sees it (held while CLK2 is low, console wiring) let mut scored = 0; let pins: &[&str] = if audio { &PINS } else { &PINS[..7] }; for (k, rec) in records.iter().enumerate() { let (clk0, clk2) = (rec[0], rec[1]); if !console || clk2 != 0 { bus = rec; } if tia.rising != (clk0 == 1) { return Err(format!("record {k}: CLK0 does not alternate")); } let prev_clk2 = if k > 0 { records[k - 1][1] } else { 0 }; let mut write = None; let selected = bus[3] == 0 && bus[4] == 0; if prev_clk2 != 0 && clk2 == 0 && selected && bus[2] == 0 { write = Some((bus[5] as u8, bus[6] as u8)); } tia.inputs = rec[7]; tia.step(write); if k < start { continue; } scored += 1; let mut dbdrv = 0; if selected && bus[2] == 1 && clk2 != 0 { let d = tia.read(bus[5] as u16); dbdrv = (if d & 0x80 != 0 { 8 } else { 4 }) | (if d & 0x40 != 0 { 2 } else { 1 }); } let ours = |p: &str| -> u32 { match p { "ph0" => tia.ph0 as u32, "rdy" => tia.rdy_low as u32, "sync" => tia.sync_low as u32, "lum" => tia.lum as u32, "col" => tia.col as u32, "blank" => tia.blank as u32, "dbdrv" => dbdrv, "au0" => tia.au0 as u32, _ => tia.au1 as u32, } }; let theirs = |p: &str| -> u32 { let column = COLUMNS.iter().position(|c| *c == p).expect("a pin column"); rec[column] }; let bad: Vec<&str> = pins.iter().copied().filter(|p| ours(p) != theirs(p)).collect(); if !bad.is_empty() { for p in &bad { *mismatches.get_mut(*p).expect("a pin") += 1; first.entry(p.to_string()).or_insert(k); } if shown < report { let detail: Vec = bad.iter().map(|p| format!("{p} {}/{}", ours(p), theirs(p))).collect(); println!( " record {k} (line step {}): {} (ours/die)", tia.step_in_line, detail.join(", ") ); shown += 1; } if let Some(stop) = stop_after { if shown >= stop { break; } } } } Ok((scored, mismatches, first, console)) } fn traces_under(dir: &Path, out: &mut Vec) { let Ok(entries) = std::fs::read_dir(dir) else { return }; for entry in entries.flatten() { let path = entry.path(); if path.is_dir() { traces_under(&path, out); } else if path.extension().is_some_and(|e| e == "trace") { out.push(path); } } } /// Every die trace under `root`: tia-fpga's (both wirings) and the local ones. pub fn die_trace_paths(root: &Path) -> Vec { let mut fpga = Vec::new(); traces_under(&root.join("reference/src/tia-fpga/sim/traces"), &mut fpga); fpga.sort(); let mut local = Vec::new(); traces_under(&root.join("tests/die_traces"), &mut local); local.sort(); fpga.extend(local); fpga } /// Each trace: (records scored, mismatches per pin, whether it passes). /// /// A trace passes when its mismatches are exactly its known departures (none /// for all but the two C27 traces). Trace names are relative to `root`. pub fn die_traces( root: &Path, tia_factory: &mut dyn FnMut() -> TIA, paths: Option>, ) -> Result, bool)>, String> { let mut results = BTreeMap::new(); for path in paths.unwrap_or_else(|| die_trace_paths(root)) { let (scored, mismatches, _, _) = replay_trace(&load_trace(&path)?, 2000, true, 0, None, tia_factory)?; let bad: BTreeMap = mismatches.into_iter().filter(|(_, n)| *n != 0).collect(); let in_local = path.components().any(|c| c.as_os_str() == "die_traces"); let name_only = path .file_name() .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_default(); let expected = if in_local { known_departures(&name_only) } else { BTreeMap::new() }; let name = match path.strip_prefix(root) { Ok(relative) => relative.display().to_string(), Err(_) => path.display().to_string(), }; let passed = bad == expected; results.insert(name, (scored, bad, passed)); } Ok(results) } // -- the RIOT timer ROMs, against console results -------------------------------- pub fn timer_set_606() -> Vec { let mut out = Vec::new(); for interval in ["TIM8T", "TIM64T", "T1024T"] { for access in ["READ", "WRITE"] { for wrap in ["1st", "2nd"] { out.push(format!("TimerTest_{interval}_{access}_{wrap}_WRAP.bin")); } } } out } fn ram_after( archive: &Path, member: &str, factory: SystemFactory, machine: Machine, frames: u64, ) -> Result, String> { let image = zip_member(archive, member)?; let cartridge = load_default(Rom::Bytes(&image)).map_err(|e| e.0)?.cartridge; let mut system = factory(cartridge, machine); system.run_frames(frames); let ram = system.board().riot.borrow().ram.clone(); Ok(ram) } /// The Stella-issue timer ROMs (#108, #606): whether each shows the console's result. /// /// The rules and the console results are the reference's tests/test_timer_roms.py /// (docs/validation.md "Milestone 3"). The results were captured on NTSC /// consoles; `machine` is handed to the factory as the other gates do, and /// a pass on another row means the NTSC console's result reproduced on that /// row, nothing more. pub fn timer_roms( root: &Path, system_factory: SystemFactory, machine: Machine, ) -> Result, String> { let issues = root.join("tests/test_roms/stella-issues"); let (t108, t606) = (issues.join("108-078-TIMER.zip"), issues.join("606-129-TimerTest.zip")); let mut results = BTreeMap::new(); let ram = ram_after(&t108, "TIMER/test1.bas.bin", system_factory, machine, 2)?; results.insert("108 test1.bas".to_string(), ram[0x13..0x16] == [0x12, 0x82, 0x46]); let ram = ram_after(&t108, "TIMER/testTIMINT_withDelay.bin", system_factory, machine, 2)?; results.insert( "108 testTIMINT_withDelay".to_string(), (ram[0x05], ram[0x06], ram[0x03]) == (0x00, 0x80, 0x00), ); let rows = 24; for member in timer_set_606() { let ram = ram_after(&t606, &member, system_factory, machine, 2)?; let (middle, right) = (&ram[rows..2 * rows], &ram[2 * rows..3 * rows]); let ok = middle.windows(2).all(|w| w[0].wrapping_sub(w[1]) == 5) && right.windows(2).all(|w| w[0].wrapping_sub(w[1]) <= 1); results.insert(format!("606 {member}"), ok); } Ok(results) } // -- ale-79's serial tables (Stella #699), one console at a time ----------------- pub const BAUD: f64 = 57600.0; // DOC: ale-79's #699 issue text, 57,600 baud 7N1 on SWCHA D7 pub const SWCHA: u16 = 0x280; // DOC: SPG pub const SERIAL_FRAME_CYCLES: u64 = 262 * 76; // the ROMs send no VSYNC: time is counted in these /// (SWCHA D7 levels as (cycle, level), CPU cycles per bit) after RESET is pressed. pub fn serial_record( rom: &[u8], machine: Machine, system_factory: SystemFactory, frames: u64, idle_frames: u64, ) -> Result<(Vec<(u64, u8)>, f64), String> { let cartridge = load(Rom::Bytes(rom), Some("4K"), None, &mame_hash(), Options::default()) .map_err(|e| e.0)? .cartridge; let mut system = system_factory(cartridge, machine); let riot = system.board().riot.clone(); let levels: Rc>> = Rc::new(RefCell::new(vec![(0, 1)])); let watched = levels.clone(); let watching_riot = riot.clone(); let observer = system.board().bus_observers.len(); system .board_mut() .bus_observers .push(Box::new(move |kind, address, value, cycle| { let to_riot = address & 0x1000 == 0 && address & 0x80 != 0; if kind == 'W' && to_riot && address & 0x2FF == SWCHA && watching_riot.borrow().ddr_a & 0x80 != 0 { let level = value >> 7; let mut levels = watched.borrow_mut(); if level != levels.last().expect("a level").1 { levels.push((cycle, level)); } } })); riot.borrow_mut().input_b &= !0x01; // RESET pressed system.run_cycles(4 * SERIAL_FRAME_CYCLES); riot.borrow_mut().input_b |= 0x01; let mut idle = 0; for _ in 0..frames { let count = levels.borrow().len(); system.run_cycles(SERIAL_FRAME_CYCLES); idle = if levels.borrow().len() == count { idle + 1 } else { 0 }; if idle >= idle_frames && levels.borrow().len() > 1 { break; } } drop(system.board_mut().bus_observers.remove(observer)); let out = levels.borrow().clone(); Ok((out, machine.timing.cpu_hz() / BAUD)) } /// The pin's levels read as a 7N1 UART would: each bit sampled in its middle. pub fn serial_decode(levels: &[(u64, u8)], period: f64) -> String { let level_at = |cycle: f64| -> u8 { let (mut lo, mut hi) = (0usize, levels.len() - 1); while lo < hi { // the last change at or before `cycle` let mid = (lo + hi + 1) / 2; if (levels[mid].0 as f64) <= cycle { lo = mid; } else { hi = mid - 1; } } levels[lo].1 }; let mut out = String::new(); let mut k = 1; while k < levels.len() { let (start, level) = levels[k]; if level != 0 { k += 1; continue; } let start = start as f64; let bits: Vec = (0..7).map(|i| level_at(start + period * (i as f64 + 1.5))).collect(); if level_at(start + period * 8.5) == 0 { out.push('\u{FFFD}'); // framing error: no stop bit } let code: u32 = bits.iter().enumerate().map(|(i, &b)| (b as u32) << i).sum(); out.push(char::from_u32(code).expect("seven bits")); let stop = start + period * 9.0; while k < levels.len() && (levels[k].0 as f64) < stop { k += 1; } } out } pub fn table_cells(text: &str) -> Vec> { text.replace('\r', "") .split('\n') .filter(|line| !line.trim().is_empty()) .map(|line| line.split_whitespace().map(String::from).collect()) .collect() } /// A cell the board and the console disagree on: (row, cell, board's, console's). pub type Miss = (usize, usize, Option, String); /// (cells matched, cells, misses as (row, cell, board's, console's)), every cell. pub fn compare_table(ours: &str, table: &str) -> (usize, usize, Vec) { let (ours_rows, rows) = (table_cells(ours), table_cells(table)); let (mut matched, mut total) = (0, 0); let mut misses = Vec::new(); for (r, row) in rows.iter().enumerate() { for (c, theirs) in row.iter().enumerate() { total += 1; let mine = ours_rows.get(r).and_then(|row| row.get(c)).cloned(); if mine.as_ref() == Some(theirs) { matched += 1; } else { misses.push((r, c, mine, theirs.clone())); } } } (matched, total, misses) } /// The seven ROMs and where each console's table is, under root (all pinned). pub fn serial_roms() -> Vec<(String, (String, String))> { let mut out = vec![ ( "early_HMOVE".to_string(), ( "reference/hardware/stella-issues/699-HMOVE_TEST.zip".to_string(), "HMOVE_TEST/early_HMOVE.bin".to_string(), ), ), ( "HMOVE_RESPx".to_string(), ( "reference/hardware/stella-issues/699-HMOVE_RESPx_test.zip".to_string(), "HMOVE_RESPx_test/HMOVE_RESPx.bin".to_string(), ), ), ]; for o in ["P0", "P1", "M0", "M1", "BL"] { out.push(( format!("HMOVE_RESPx_{o}"), ( "tests/test_roms/stella-issues/699-140-HMOVE_RESPx_v2.zip".to_string(), format!("HMOVE_RESPx_{o}.bin"), ), )); } out } pub const CONSOLES: [&str; 6] = [ "PAL_7800", "PAL_JR_84", "PAL_JR_91", "PAL_L6", "PAL_VADER", "SECAM_WOODY", ]; /// One console's pinned result table for one of the seven ROMs. pub fn serial_table_text(root: &Path, rom: &str, console: &str) -> Result { let (archive, name) = if rom == "early_HMOVE" { let member = match console { "PAL_VADER" => "PAL_vader", "SECAM_WOODY" => "SECAM_woody", other => other, }; ( root.join("reference/hardware/stella-issues/699-HMOVE_TEST.zip"), format!("HMOVE_TEST/{member}.txt"), ) } else if rom == "HMOVE_RESPx" { ( root.join("reference/hardware/stella-issues/699-HMOVE_RESPx_test.zip"), format!("HMOVE_RESPx_test/Results/HMOVE_RESPx_{console}.txt"), ) } else { let object = rom.rsplit('_').next().unwrap_or(rom); ( root.join("reference/hardware/stella-issues/699-results.zip"), format!("test_{object}_{console}.txt"), ) }; let bytes = zip_member(&archive, &name)?; Ok(bytes.iter().map(|&b| b as char).collect()) // latin-1 } pub fn serial_rom(root: &Path, rom: &str) -> Result, String> { let roms = serial_roms(); let (_, (archive, member)) = roms .iter() .find(|(name, _)| name == rom) .ok_or_else(|| format!("no serial ROM {rom}"))?; zip_member(&root.join(archive), member) } /// Each ROM decoded from the board running `machine`, against `console`'s /// table: (cells matched, cells, misses). Every cell counts. pub fn serial_tables( root: &Path, machine: Machine, console: &str, roms: Option<&[&str]>, system_factory: SystemFactory, ) -> Result)>, String> { let all: Vec = serial_roms().into_iter().map(|(name, _)| name).collect(); let names: Vec = match roms { Some(list) => list.iter().map(|s| s.to_string()).collect(), None => all, }; let mut results = BTreeMap::new(); for rom in names { let (levels, period) = serial_record(&serial_rom(root, &rom)?, machine, system_factory, 20000, 30)?; let text = serial_decode(&levels, period); results.insert( rom.clone(), compare_table(&text, &serial_table_text(root, &rom, console)?), ); } Ok(results) } // -- frame hashes and lockstep against this board -------------------------------- pub const NO_INTRO_SET: &str = "Atari - Atari 2600"; pub fn dump_path(name: &str) -> Result { match std::env::var("NO_INTRO_DIR") { Ok(base) if !base.is_empty() => Ok(Path::new(&base).join(NO_INTRO_SET).join(format!("{name}.zip"))), _ => Err("set NO_INTRO_DIR to the No-Intro root".to_string()), } } pub const SMOKE_LIST: &str = "tests/smoke_dumps.txt"; /// The smoke list, `tests/smoke_dumps.txt` under `root`: No-Intro dump names /// in file order ('#' starts a comment). The dumps worth rerunning after a change, /// before a full sweep (methodology, "Smoke before sweep"); scripts/sweep_stella.py /// and a transcription's lockstep read it here. pub fn smoke_names(root: &Path) -> Result, String> { let text = std::fs::read_to_string(root.join(SMOKE_LIST)).map_err(|e| e.to_string())?; Ok(text .lines() .map(|line| line.split('#').next().unwrap_or("").trim()) .filter(|line| !line.is_empty()) .map(String::from) .collect()) } fn hex(digest: &[u8]) -> String { digest.iter().map(|b| format!("{b:02x}")).collect() } /// SHA-256 of every finished line's pixels, every audio sample and the 6507's /// registers and cycle count at each frame's end, over `frames` frames. pub fn run_hashes(system: &mut System, frames: u64) -> BTreeMap { let pixels = Rc::new(RefCell::new(Sha256::new())); let (mut audio, mut registers) = (Sha256::new(), Sha256::new()); let previous = Rc::new(RefCell::new(system.board_mut().tia.on_line.take())); { let (pixels, previous) = (pixels.clone(), previous.clone()); system.board_mut().tia.on_line = Some(Box::new(move |tia: &TIA| { pixels.borrow_mut().update(&tia.pixels); if let Some(callback) = previous.borrow_mut().as_mut() { callback(tia); } })); } for _ in 0..frames { system.run_frames(1); let samples = system.board_mut().tia.audio.take_samples(); for s in samples { audio.update(s.to_le_bytes()); } let cpu = &system.cpu; let mut packed = Vec::with_capacity(15); packed.extend_from_slice(&cpu.pc.to_le_bytes()); packed.extend_from_slice(&[cpu.a, cpu.x, cpu.y, cpu.s, cpu.p]); packed.extend_from_slice(&system.board().cycles.to_le_bytes()); registers.update(&packed); } system.board_mut().tia.on_line = previous.borrow_mut().take(); let pixels = hex(&pixels.borrow().clone().finalize()); let (audio, registers) = (hex(&audio.finalize()), hex(®isters.finalize())); let whole = hex(&Sha256::digest(format!("{pixels}{audio}{registers}").as_bytes())); BTreeMap::from([ ("run".to_string(), whole), ("pixels".to_string(), pixels), ("audio".to_string(), audio), ("registers".to_string(), registers), ]) } /// The line `tests/frame_hashes.tsv` keeps for a run. pub fn hash_row(name: &str, frames: u64, hashes: &BTreeMap) -> String { format!( "{name}\t{frames}\t{}\t{}\t{}\t{}", &hashes["run"][..16], &hashes["pixels"][..16], &hashes["audio"][..16], &hashes["registers"][..16] ) } /// `tests/frame_hashes.tsv` under `root`: dump name -> recorded line. pub fn recorded_hashes(root: &Path) -> Result, String> { let text = std::fs::read_to_string(root.join("tests/frame_hashes.tsv")).map_err(|e| e.to_string())?; Ok(text .lines() .filter(|row| !row.is_empty() && !row.starts_with('#')) .map(|row| (row.split('\t').next().unwrap_or("").to_string(), row.to_string())) .collect()) } /// Each recorded dump run on the candidate: whether its line equals the record. pub fn frame_hashes( root: &Path, names: Option>, system_factory: SystemFactory, machine: Machine, ) -> Result, String> { let expected = recorded_hashes(root)?; let mut results = BTreeMap::new(); for name in names.unwrap_or_else(|| expected.keys().cloned().collect()) { let record = expected.get(&name).ok_or_else(|| format!("{name} is not recorded"))?; let frames: u64 = record .split('\t') .nth(1) .and_then(|f| f.parse().ok()) .ok_or("bad record")?; let path = dump_path(&name)?; let cartridge = load_default(Rom::Path(&path)).map_err(|e| e.0)?.cartridge; let mut system = system_factory(cartridge, machine); results.insert( name.clone(), hash_row(&name, frames, &run_hashes(&mut system, frames)) == *record, ); } Ok(results) } /// One bus cycle as `Board.bus_observers` sees it: (kind, address, value). pub type Cycle = (char, u16, u8); /// The candidate and this board side by side, every bus cycle compared. /// /// Returns (cycles that agreed, the first difference as (index, ours, theirs) /// or None). A cycle is (kind, address, value) as `Board.bus_observers` /// sees it, counted from power-on on each side (halted cycles make no /// access); both run from the same cartridge image and machine row. pub fn lockstep( image: &[u8], system_factory: SystemFactory, machine: Machine, cycles: usize, ) -> Result<(usize, Option<(usize, Cycle, Cycle)>), String> { let build = |factory: SystemFactory| -> Result<(System, Rc>>), String> { let log: Rc>> = Rc::new(RefCell::new(Vec::new())); let mut system = factory(load_default(Rom::Bytes(image)).map_err(|e| e.0)?.cartridge, machine); let writer = log.clone(); system .board_mut() .bus_observers .push(Box::new(move |k, a, v, _c| writer.borrow_mut().push((k, a, v)))); Ok((system, log)) }; let (mut ours, ours_log) = build(&default_system)?; let (mut theirs, theirs_log) = build(system_factory)?; let mut agreed = 0; while agreed < cycles { ours.step(); theirs.step(); let (mut a, mut b) = (ours_log.borrow_mut(), theirs_log.borrow_mut()); let n = a.len().min(b.len()); for k in 0..n { if a[k] != b[k] { return Ok((agreed + k, Some((agreed + k, a[k], b[k])))); } } agreed += n; a.drain(..n); b.drain(..n); } Ok((agreed, None)) }